前面說過為HTML元素添加自訂的屬性,是通過手動在HTML控制項中加上,其實可以在javascript中動態添加:如有一文字框:
<input type="text" id="txtInput" name="txtInput" value="自訂文本">
如想增加idvalue屬性(值為”自訂值”),可以在javascript中這樣寫:
var txt = document.getElementById("txtInput");
txt.setAttribute("idvalue","自訂值");
setAttribute中第一個參數是指明自訂屬性的名稱,第二個參數是初始值
代碼如下:<html>
<head>
<title>用javascript添加控制項自訂屬性</title>
<script language="javascript">
function addCustomAttribute()
{
var txt = document.getElementById("txtInput");
txt.setAttribute("idvalue","自訂值");
}
function showIdValue()
{
var txt = document.getElementById("txtInput");
alert(txt.attributes["idvalue"].nodeValue);
}
</script>
</head>
<body onload="addCustomAttribute();">
<input type="text" id="txtInput" name="txtInput" value="自訂文本">
<input type="button" value="顯示idValue" onclick="showIdValue();">
</body>
</html>
原始碼:http://files.cnblogs.com/redleaf1995/jsCustom.rar