问题描述
是否已开发出使用 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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)