何时在 JavaScript 中使用 setAttribute 与 .attribute= ? [英] When to use setAttribute vs .attribute= in JavaScript?

查看:34
本文介绍了何时在 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= ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆