正如标题所示,它们有什么区别?
我想后者至少能做前者能做的事。我的观点对吗?
p。S: obj是一个DOM元素
setAttribute
是一个DOM Element方法——它只能用于DOM元素。如果您尝试在自己的对象上使用它,则会抛出TypeError
,因为它们不支持该方法,除非您自己创建它。例如:
var myObject = {};
myObject.setAttribute('foo', 'bar'); // this will throw a TypeError
var myDiv = document.createElement('div');
myDiv.setAttribute('foo', 'bar'); // this works fine
但是,您描述的第二个方法是将属性和方法分配给您自己的对象和DOM对象的有效方法(大多数浏览器中都有一些针对DOM对象的特殊方法,例如onclick,就像您看到的那样)。
var myObject = {};
myObject.foo = 'bar';
console.log(myObject.foo); // --> 'bar'
console.log(myObject['foo']); // --> 'bar'
var myDiv = document.createElement('div');
myDiv.foo = 'bar';
myDiv.onclick = function() { console.log('clicked!') };
// same as: <div foo="bar" onclick="function() {console.log('clicked'!) }"></div>
您可以在这里阅读有关Element接口和支持的方法的更多信息:http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614(向下滚动一点setAttribute)
一个设置属性,另一个设置属性。
一些属性直接映射到具有相同名称的属性(如<input type="password">
和myInput.type), some do not (such as
and
myInput)。className . Some properties do not have an attribute (such as
myDiv.getElementsByTagName ').
Internet Explorer 7及更低版本(以及Quirks模式下的新ie)有一个bug,即setAttribute
直接映射到同名的属性,无论属性和属性是否相互映射。
请注意,方括号符号使用字符串而不是标识符,因此您可以访问无法用标识符表示的对象上的属性。例如,foo.bar
和foo['bar']
是相同的,但foo['bar-bar']
不能使用点表示法表示)。
最大的区别在于变量名——以下面的例子为例:
obj.what-ever = value;
/// syntax error - the parser attempts to subtract obj.what
/// from the nonexistent variable 'ever'.
obj.setAttribute('what-ever',value);
/// this works!
还有,我想说的是,obj。setAttribute不是一个原生javascript方法——原生地,你会在一个对象上设置一个键,它的名字是不允许的,像这样:obj['@#^&*^'] = value;
希望有帮助!