前面說過爲HTML元素添加自定義的屬性,是通過手動在HTML控件中加上,其實可以在javascript中動態添加:如有一文本框:
<input type="text" id="txtInput" name="txtInput" value="自定義文本">
如想增加idvalue屬性(值爲”自定義值”),可以在javascript中這樣寫:
var txt = document.getElementById("txtInput");
txt.setAttribute("idvalue","自定義值");
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>
<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://www.cnblogs.com/Files/redleaf1995/jsCustom.rar