Can I add custom attribute to HTML tag?

2018-12-31 14:14发布

Can I add custom attribute to HTML tag like this: <tag myAttri="myVal" />

13条回答
时光乱了年华
2楼-- · 2018-12-31 14:38

You can add, but then you have to write a line of javascript too:

document.createElement('tag');

to make sure everything fall in place. I mean IE :)

查看更多
看风景的人
3楼-- · 2018-12-31 14:39

You can do it in a native way with JavaScript:

element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter
查看更多
与君花间醉酒
4楼-- · 2018-12-31 14:40

You can amend your !DOCTYPE declaration (i.e. DTD) to allow it, so that the [XML] document will still be valid:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
  <!ATTLIST tag myAttri CDATA #IMPLIED>
]>

#IMPLIED means it is an optional attribue, or you could use #REQUIRED, etc.

more info here:

http://www.w3schools.com/xml/xml_dtd_attributes.asp

查看更多
深知你不懂我心
5楼-- · 2018-12-31 14:40

No, this will break validation.

In HTML 5 you can/will be able to add custom attributes. Something like this:

<tag data-myAttri="myVal" />
查看更多
永恒的永恒
6楼-- · 2018-12-31 14:43

Another approach, which is clean and will keep the document valid, is to concatenate the data you want into another tag e.g. id, then use split to take what you want when you want it.

<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>
查看更多
梦寄多情
7楼-- · 2018-12-31 14:46

var demo = document.getElementById("demo")
console.log(demo.dataset.myvar)
// or
alert(demo.dataset.myvar)
//this will show in console the value of myvar
<div id="demo" data-myvar="foo">anything</div>

查看更多
登录 后发表回答