使用createAttribute与直接设置属性?

Don*_*ghn 9 javascript

在javascript中,我们可以通过以下方式创建一个新的DOM元素......

通过使用createAttribute()+ setAttributeNode()dom方法:

var input = document.createElement("input"),
    type = document.createAttribute("type");

type.nodeValue = "text";
input.setAttributeNode(type);
container.appendChild(input);
Run Code Online (Sandbox Code Playgroud)

或者直接设置属性:

var input = document.createElement("input");

input.type = "text";
container.appendChild(input);
Run Code Online (Sandbox Code Playgroud)

即使每个元素只有几个属性,后者最终可能会减少相当多的代码.

问题:有没有人遇到后一种方法的任何缺点(直接设置属性)?

我在几个浏览器(最新的FF,IE,Safari,Opera,旧IE甚至IE6工作)和基本测试(插入带有type,name和maxLength属性的文本输入)上测试了它们都通过了. 如果有人需要,这就是小提琴.

小智 11

document.createAttribute
document.createAttributeNS
element.getAttributeNode
element.getAttributeNodeNS
... and a lot of others
Run Code Online (Sandbox Code Playgroud)

将在DOM4中弃用,所以不要使用它,只需使用setAttribute("name","value")进行设置

http://www.w3.org/TR/dom/#element

someinput.type不同,基本上是做的捷径

setAttribute("type","text");
getAttribute("text");
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

element._some_attribute_ is not available for all attributes, just some:
element.dir
element.lang
element.id
...etc
Run Code Online (Sandbox Code Playgroud)

  • 使用`setAttribute()`和`getAttribute()`总是等同于使用相应的属性,这并不完全正确.例如,`value`属性(总是反映输入的当前值)与`value`属性(仅代表初始值)分开存在.一个更明显的例子是`style`属性,它包含一个字符串,而`style`属性是一个`CSSStyleDeclaration`对象,它具有每个单独样式属性的各个属性. (2认同)