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=?
基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
