使用createAttribute与直接设置属性? [英] Using createAttribute vs. just setting the attribute directly?

查看:65
本文介绍了使用createAttribute与直接设置属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In javascript, we can create a new DOM element in the following ways...

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

By using the createAttribute() + setAttributeNode() dom methods:

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);

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

The latter can end up being quite lot less code, even when there are only a couple attributes per element.

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

The question: has anyone run across any drawbacks of the latter method (setting attributes directly)?

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

I tested this on several browsers (the latest FF, IE, Safari, Opera, old IEs - even IE6 worked) and on a basic test (inserting a text input with type, name, and maxLength attributes) they all passed. Here's the fiddle if anybody needs it.

推荐答案

document.createAttribute
document.createAttributeNS
element.getAttributeNode
element.getAttributeNodeNS
... and a lot of others

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

will be deprecated in DOM4, so don't use it, just set with setAttribute("name","value")

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

someinput.type不同
基本上是执行的快捷方式

someinput.type is different basically is a shortcut for doing

setAttribute("type","text");
getAttribute("text");

希望这会有所帮助!

element._some_attribute_ is not available for all attributes, just some:
element.dir
element.lang
element.id
...etc

这篇关于使用createAttribute与直接设置属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆