是否已经开发了使用setAttribute代替点(.)属性表示法的最佳实践?
例如:
myObj.setAttribute("className", "nameOfClass");
myObj.setAttribute("id", "someID");
or
myObj.className = "nameOfClass";
myObj.id = "someID";
是否已经开发了使用setAttribute代替点(.)属性表示法的最佳实践?
例如:
myObj.setAttribute("className", "nameOfClass");
myObj.setAttribute("id", "someID");
or
myObj.className = "nameOfClass";
myObj.id = "someID";
当前回答
在元素上设置属性(例如class)的方法: 1. 埃尔。className = string 2. el.setAttribute(‘类’,字符串) 3.el.attributes.setNamedItem(对象) 4. el.setAttributeNode(节点)
我做了一个简单的基准测试(这里)
似乎setAttributeNode比使用setAttribute快3倍。
所以如果性能是一个问题-使用“setAttributeNode”
其他回答
谷歌API脚本对此进行了有趣的观察:
他们是这样做的:
var scriptElement = document.createElement("script");
scriptElement = setAttribute("src", "https://some.com");
scriptElement = setAttribute("nonce", "https://some.com");
scriptElement.async = "true";
注意,他们如何为"src"和"nonce"使用setAttribute,但是。async =…对于“async”属性。
我不是100%确定,但可能是因为“async”只在支持直接。attr =赋值的浏览器上被支持。因此,尝试setAttribute("async")是没有意义的,因为如果浏览器不理解.async=…它不会理解“async”属性。
希望这是我正在进行的“非最小化GAPI”研究项目的有益见解。如果我说错了,请指正。
在元素上设置属性(例如class)的方法: 1. 埃尔。className = string 2. el.setAttribute(‘类’,字符串) 3.el.attributes.setNamedItem(对象) 4. el.setAttributeNode(节点)
我做了一个简单的基准测试(这里)
似乎setAttributeNode比使用setAttribute快3倍。
所以如果性能是一个问题-使用“setAttributeNode”
这看起来像是使用setAttribute更好的一种情况:
高效的JavaScript
var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
'color: ' + newColor + ';' +
'border: ' + newBorder + ';';
if(typeof(posElem.style.cssText) != 'undefined') {
posElem.style.cssText = newStyle;
} else {
posElem.setAttribute('style', newStyle);
}
“在JavaScript中什么时候使用setAttribute vs .attribute= ?”
一般的规则是使用.attribute并检查它是否在浏览器上工作。
..如果它可以在浏览器上运行,那么就可以开始了。
..如果没有,使用. setattribute (attribute, value)来代替该属性的.attribute。
冲洗-重复所有属性。
如果你很懒,你可以简单地使用. setattribute。这在大多数浏览器上都可以正常工作。(尽管支持.attribute的浏览器可以比. setattribute (attribute, value)更好地优化它。)
来自Javascript: The Definitive Guide,它澄清了一些事情。它注意到HTML文档的HTMLElement对象定义了与所有标准HTML属性对应的JS属性。
因此,您只需要对非标准属性使用setAttribute。
例子:
node.className = 'test'; // works
node.frameborder = '0'; // doesn't work - non standard attribute
node.setAttribute('frameborder', '0'); // works