何时在 JavaScript 中使用 setAttribute 与 .attribute=?
是否已开发出使用 setAttribute
而不是点 (.
) 属性表示法的最佳实践?
Has a best-practice around using setAttribute
instead of the dot (.
) attribute notation been developed?
例如:
myObj.setAttribute("className", "nameOfClass");
myObj.setAttribute("id", "someID");
或
myObj.className = "nameOfClass";
myObj.id = "someID";
推荐答案
如果您想在 JavaScript 中进行编程访问,您应该始终使用直接的 .attribute
形式(但请参阅下面的 quirksmode 链接).它应该正确处理不同类型的属性(想想onload").
You should always use the direct .attribute
form (but see the quirksmode link below) if you want programmatic access in JavaScript. It should handle the different types of attributes (think "onload") correctly.
当您希望按原样处理 DOM(例如,仅文本)时,请使用 getAttribute
/setAttribute
.不同的浏览器混淆了两者.请参阅怪癖模式:属性(in)兼容性.
Use getAttribute
/setAttribute
when you wish to deal with the DOM as it is (e.g. literal text only). Different browsers confuse the two. See Quirks modes: attribute (in)compatibility.
相关文章