Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

javascript - 什么时候在JavaScript中使用setAttribute vs .attribute =?(When to use setAttribute vs .attribute= in JavaScript?)

Has a best-practice around using setAttribute instead of the dot ( . ) attribute notation been developed?

(是否已开发出围绕setAttribute而不是点( . )属性符号的最佳实践?)

Eg:

(例如:)

myObj.setAttribute("className", "nameOfClass");
myObj.setAttribute("id", "someID");

or

(要么)

myObj.className = "nameOfClass";
myObj.id = "someID";
  ask by Francisc translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From Javascript: The Definitive Guide , it clarifies things.

(从Javascript:权威指南中 ,它可以使事情变得清晰 。)

It notes that HTMLElement objects of a HTML doc define JS properties that correspond to all standard HTML attributes.

(它指出HTML文档的HTMLElement对象定义了与所有标准HTML属性相对应的JS属性。)

So you only need to use setAttribute for non-standard attributes.

(因此,您只需要对非标准属性使用setAttribute 。)

Example:

(例:)

node.className = 'test'; // works
node.frameborder = '0'; // doesn't work - non standard attribute
node.setAttribute('frameborder', '0'); // works

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...