怎么使用js为html元素添加自定义属性

如何使用js为html元素添加自定义属性

如何使用js为html元素添加自定义属性:
html元素在默认情况下是具有一些自带的属性的,例如<input>标签一般具有name和value属性,但是在实际应用中,可能使用自定的属性更为方便一些,当然具体场景这里就不介绍了,肯定有这样的需求,下面就通过代码实例介绍一下如何实现此功能。
代码如下:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>自定义属性-蚂蚁部落</title> 
<script type="text/javascript">
function addCustomAttribute()
{
  var txt=document.getElementById("txtInput");
  txt.setAttribute("idvalue","自定义值");
}
function showIdValue()
{
  var txt=document.getElementById("txtInput");
  alert(txt.attributes["idvalue"].nodeValue);
}
window.onload=function()
{
  var bt=document.getElementById("bt");
  addCustomAttribute();
  bt.onclick=function()
  {
    showIdValue();
  }
}
</script>
</head>
<body>
<input type="text" id="txtInput" name="txtInput" value="自定义文本"/>
<input type="button" id="bt" value="显示idValue"/>
</body>
</html>

 以上代码实现了我们的要求,为文本框添加了自定义的属性idvalue,并设置属性值。

实现此功能的核心是采用了setAttribute()函数,此函数具有一定的浏览器兼容性问题,这里就不介绍了,具体可以参阅setAttribute()函数的用法详解IE6和IE7是否支持setAttribute()函数一章节。  

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=10755

更多内容可以参阅:http://www.softwhy.com/javascript/