我可以像下面这样向HTML标记添加自定义属性吗?

<tag myAttri="myVal" />

当前回答

另一种干净的方法是将你想要的数据连接到另一个标签中,例如id,然后使用split来获取你想要的东西。

<html>
<script>
  function demonstrate(){
    var x = document.getElementById("example data").querySelectorAll("input");
    console.log(x);
    for(i=0;i<x.length;i++){
      var line_to_illustrate = x[i].id  + ":" + document.getElementById ( x[i].id ).value;
      //concatenated values
      console.log("this is all together: " + line_to_illustrate); 
      //split values
      var split_line_to_illustrate = line_to_illustrate.split(":");
      for(j=0;j<split_line_to_illustrate.length;j++){
        console.log("item " + j+ " is: " + split_line_to_illustrate[j]);
      }      
    }
  }
</script> 

<body>

<div id="example data">
  <!-- consider the id values representing a 'from-to' relationship -->
  <input id="1:2" type="number" name="quantity" min="0" max="9" value="2">
  <input id="1:4" type="number" name="quantity" min="0" max="9" value="1">
  <input id="3:6" type="number" name="quantity" min="0" max="9" value="5">  
</div>

<input type="button" name="" id="?" value="show me" onclick="demonstrate()"/>

</body>
</html>

其他回答

是的,你能做到!

有下一个HTML标签:

<tag key="value"/>

我们可以用JavaScript访问它们的属性:

element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter

Element.setAttribute()如果该属性不存在,则将其放在HTML标记中。所以,如果你要用JavaScript设置它,你不需要在HTML代码中声明它。

Key:可以是属性的任意名称,而当前标记尚未使用。 值:它总是包含你需要的字符串。

您可以随意向元素添加自定义属性。但这会使您的文件无效。

在HTML 5中,您将有机会使用自定义数据属性前缀data-。

另一种干净的方法是将你想要的数据连接到另一个标签中,例如id,然后使用split来获取你想要的东西。

<html>
<script>
  function demonstrate(){
    var x = document.getElementById("example data").querySelectorAll("input");
    console.log(x);
    for(i=0;i<x.length;i++){
      var line_to_illustrate = x[i].id  + ":" + document.getElementById ( x[i].id ).value;
      //concatenated values
      console.log("this is all together: " + line_to_illustrate); 
      //split values
      var split_line_to_illustrate = line_to_illustrate.split(":");
      for(j=0;j<split_line_to_illustrate.length;j++){
        console.log("item " + j+ " is: " + split_line_to_illustrate[j]);
      }      
    }
  }
</script> 

<body>

<div id="example data">
  <!-- consider the id values representing a 'from-to' relationship -->
  <input id="1:2" type="number" name="quantity" min="0" max="9" value="2">
  <input id="1:4" type="number" name="quantity" min="0" max="9" value="1">
  <input id="3:6" type="number" name="quantity" min="0" max="9" value="5">  
</div>

<input type="button" name="" id="?" value="show me" onclick="demonstrate()"/>

</body>
</html>

使用任何数据,我经常使用它们

<aside data-area="asidetop" data-type="responsive" class="top">

是的,你可以,你在问题本身做到了:<html myAttri="myVal"/>。