Javascript:添加属性方法问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7203820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:20:00  来源:igfitidea点击:

Javascript: add attribute method question

javascriptattributes

提问by sid_com

Possible Duplicate:
JavaScript setAttribute vs .attribute=

可能重复:
JavaScript setAttribute vs .attribute=

Should I prefer one of these two methods to add attributes?

我应该更喜欢这两种方法之一来添加属性吗?

input.name='amount';

input.setAttribute('name', 'amount');

回答by Manse

setAttribute doesn't work correctly in IE

setAttribute 在 IE 中无法正常工作

http://www.quirksmode.org/dom/w3c_core.html#attributes

http://www.quirksmode.org/dom/w3c_core.html#attributes

回答by Amulya Khare

From MDN:

来自MDN

Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use elt.value instead of elt.setAttribute('value', val).

使用 setAttribute() 修改某些属性,尤其是 XUL 中的值,工作不一致,因为该属性指定了默认值。要访问或修改当前值,您应该使用属性。例如,使用 elt.value 而不是 elt.setAttribute('value', val)。

I guess it would be better to access attributes directly, since that is what the DOM is designed for...

我想直接访问属性会更好,因为这就是 DOM 的设计目的......

回答by Kris

Mozilla supports only setAttribute(). So if you are designing a multi-browser supporting page, it will be good to have an if condition checking the Browser Name, and call the function/assignments as per that.

Mozilla 仅支持 setAttribute()。因此,如果您正在设计一个多浏览器支持页面,最好有一个检查浏览器名称的 if 条件,并据此调用函数/赋值。