When to use setAttribute vs .attribute= in JavaScript?(何时在 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.
这篇关于何时在 JavaScript 中使用 setAttribute 与 .attribute=?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:何时在 JavaScript 中使用 setAttribute 与 .attribute=?


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01