問題描述
是否已開發出使用 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.
這篇關于何時在 JavaScript 中使用 setAttribute 與 .attribute=?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!