首页 > 解决方案 > 如何计算用户在 html 中写入的属性名称和值的数量

问题描述

我想创建一个函数来计算我在 html 中输入的属性名称和值有多少属性。

我不知道如何按属性名称和值计算!

就像我在这个 html 中输入“类型”和“文本”然后显示 2!

我对javascript很陌生!如果您帮助我,将非常感激!谢谢

function javascript_click() { 
  if (document.getElementById("value3").value && document.getElementById("value4").value ) {
    var attName=document.getElementById("value3").value;
    var attValue=document.getElementById("value4").value;
    if((attName && attValue) !==''){
      var val3 = document.getElementById("value3");}
    else {
      document.getElementById("cnt").innerHTML += 
      "wrong value of ID <br>";
    }
  }
}
<form action="">
  <table class="tg" id="tg">
    <tr>
      <td>Attribute name</td>
      <td><input type="text" id="value3"></td>
    </tr>
    <tr>
      <td>attribute value</td>
      <td><input type="text" id="value4"></td>
    </tr>
  </table>
  <div id="cnt"></div>
</form>
<div class="button">
  <button id='btn_javascript' onclick="javascript_click();">javascript</button>
</div>

标签: javascriptjqueryhtml

解决方案


每次用户输入一对属性时,我都会将属性推送到数组attRy中。

attRy.length会给你属性对的数量。

let attRy = []

function javascript_click() { 
  if (value3.value && value4.value ) {
    var attName = value3.value;
    var attValue = value4.value;
    if(attName !=='' && attValue !==''){
      attRy.push(attName + ": " +attValue);
      cnt.innerHTML = attRy.length +" attributes:<br>";
      attRy.forEach((a) =>{
        cnt.innerHTML += a + "<br>"
      })
      
      }
    else {
      cnt.innerHTML += 
      "wrong value of ID <br>";
    }
  }
}
<form action="">
  <table class="tg" id="tg">
    <tr>
      <td>Attribute name</td>
      <td><input type="text" id="value3"></td>
    </tr>
    <tr>
      <td>attribute value</td>
      <td><input type="text" id="value4"></td>
    </tr>
  </table>
  <div id="cnt"></div>
</form>
<div class="button">
  <button id='btn_javascript' onclick="javascript_click();">javascript</button>
</div>


推荐阅读