关于JavaScript新建对象的属性如何设置
var para = document.createElement("div");
var a = document.createElement("a");
//第一种写法
var att1 = document.createAttribute("class");
att1.value = "div1";
para.setAttributeNode(att1);
var att2 = document.createAttribute("href");
att2.value = "javaScript:void(0)";
a.setAttributeNode(att2);
//第二种写法
a.setAttribute("onclick","this.parentNode.remove()");
不能用
a.onclick = "值";
会报错
本文介绍了两种在JavaScript中为元素创建和设置属性的方法:通过`createAttribute`和`setAttributeNode`,以及直接使用`setAttribute`。示例代码展示了如何为`div`和`a`元素添加`class`和`href`属性。注意,为`a`元素设置`onclick`事件时,不能直接赋值字符串,应当使用表达式避免语法错误。
1269

被折叠的 条评论
为什么被折叠?



