前面說過為HTML元素添加自定義的屬性,是通過手動在HTML控件中加上,其實可以在javascript中動態(tài)添加:如有一文本框:
復制代碼 代碼如下:
<input type="text" value="自定義文本">
復制代碼 代碼如下:
var txt = document.getElementById("txtInput");
txt.setAttribute("idvalue","自定義值");
代碼如下:
復制代碼 代碼如下:
<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>
<input type="text" value="自定義文本">
<input type="button" value="顯示idValue">
</body>
</html>
新聞熱點
疑難解答
圖片精選