是否已开发出使用 setAttribute
而不是点 (.
) 属性表示法的最佳实践?
例如:
myObj.setAttribute("className", "nameOfClass");
myObj.setAttribute("id", "someID");
或
myObj.className = "nameOfClass";
myObj.id = "someID";
最佳答案
来自 Javascript: The Definitive Guide ,它澄清了事情。它指出 HTMLElement HTML 文档的对象定义了与所有标准 HTML 属性相对应的 JS 属性。
所以你只需要对非标准属性使用setAttribute
。
例子:
node.className = 'test'; // works
node.frameborder = '0'; // doesn't work - non standard attribute
node.setAttribute('frameborder', '0'); // works
关于javascript - 何时在 JavaScript 中使用 setAttribute 与 .attribute=?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3919291/