在javascript中,我们可以通过以下方式创建一个新的DOM元素...
通过使用 createAttribute() + setAttributeNode() dom 方法:
var input = document.createElement("input"),
type = document.createAttribute("type");
type.nodeValue = "text";
input.setAttributeNode(type);
container.appendChild(input);
或者直接设置属性:
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
后者最终可以减少很多代码,即使每个元素只有几个属性。
问题:有没有人遇到过后一种方法(直接设置属性)的缺点?
我在多个浏览器(最新的 FF、IE、Safari、Opera、旧的 IE - 甚至 IE6 也能工作)和基本测试(插入带有类型、名称和 maxLength 属性的文本输入)上进行了测试,它们都通过了。 Here's the fiddle如果有人需要的话。
最佳答案
document.createAttribute
document.createAttributeNS
element.getAttributeNode
element.getAttributeNodeNS
... and a lot of others
在 DOM4 中将被弃用,所以不要使用它,只需使用 setAttribute("name","value") 设置
http://www.w3.org/TR/dom/#element
someinput.type 不同 基本上是做事的捷径
setAttribute("type","text");
getAttribute("text");
希望这对您有所帮助!
element._some_attribute_ is not available for all attributes, just some:
element.dir
element.lang
element.id
...etc
关于javascript - 使用 createAttribute 还是直接设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7677930/