在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)
| 归档时间: |
|
| 查看次数: |
8983 次 |
| 最近记录: |