Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...