修改方法:1、使用setAttribute()方法修改节点属性的值,语法“节点.setAttribute(属性名,值)”;2、使用removeAttribute()方法删除指定的属性,语法“节点.removeAttribute(属性名)”。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
javascript修改元素节点的属性
setAttribute() 方法设置属性值
使用元素的 setAttribute() 方法可以设置元素的属性值。用法如下:
setAttribute(name, value)
参数 name 和 value 分别表示属性名称和属性值。属性名和属性值必须以字符串的形式进行传递。如果元素中存在指定的属性,它的值将被刷新;如果不存在,则 setAttribute() 方法将为元素创建该属性并赋值。
<div id=red>红盒子</div> <div id=blue>蓝盒子</div> <script> var red = document.getElementById(red); //获取红盒子的引用 var blue= document.getElementById(blue); //获取蓝盒子的引用 red.setAttribute(title, 这是红盒子); //为红盒子对象设置title属性和值 blue.setAttribute(title, 这是蓝盒子); //为蓝盒子对象设置title属性和值 </script>
removeAttribute() 方法删除属性
使用元素的 removeAttribute() 方法可以删除指定的属性。用法如下:
removeAttribute(name)
参数 name 表示元素的属性名。
示例:
<script> window.onload = function () { //绑定页面加载完毕时的事件处理函数 var table = document.getElementByTagName(table)[0]; //获取表格外框的引用 var del = document.getElementById(del); var reset = document.getElementById(reset); del.onclick = function () { table.removeAttribute(border); } reset.onclick = function () { table.setAttribute(border, 2); } </script> <table width=100% border=2> <tr> <td>数据表格</td> <tr> </table> <button id=del>删除</button><button id=reset>恢复</button>
在上面示例中设计了两个按钮,并分别绑定了不同的事件处理函数。单击“删除”按钮即可调用表格的 removeAttribute() 方法清除表格边框,单击“恢复”按钮即可调用表格的 setAttribute() 方法重新设置表哥便可的粗细。
【相关推荐:javascript学习教程】
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。