前面说过为HTML元素添加自定义的属性,是通过手动在HTML控件中加上,其实可以在javascript中动态添加:如有一文本框:
复制代码 代码如下:
复制代码
<input type="text" id="txtInput" name="txtInput" value="自定义文本">
<input type="text" id="txtInput" name="txtInput" value="自定义文本">
如想增加idvalue属性(值为”自定义值”),可以在javascript中这样写:
复制代码 代码如下:
复制代码
var txt = document.getElementById("txtInput");
txt.setAttribute("idvalue","自定义值");
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>
<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>
最后
以上就是复杂篮球最近收集整理的关于用javascript添加控件自定义属性解析的全部内容,更多相关用javascript添加控件自定义属性解析内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复