是否已经开发了使用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";
当前回答
这看起来像是使用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);
}
其他回答
增加2个与.textContent和.innerHTML相关的点
<div id="mydiv"></div>
var elem = document.getElementById("mydiv");
elem.textContent = "hello"; // OK - Content has been updated
elem.setAttribute("textContent", "hello"); // NOT OK - You are trying to set
// the attribute than it's content
elem.innerHTML = "world"; // OK - Content has been updated
elem.setAttribute("innerHTML", "world"); // NOT OK - You are trying to set
// the attribute than it's content
If the element you are referring to does not already include a Javascript object property for a given attribute (as others have described), then setting that property will not propagate the change back to the DOM, it just adds the named property to the Javascript object, and the DOM ignores it. For example, getting the element mySpan by id and then doing mySpan.class = 'warning' will do nothing, whether or not the span element in question already has a class attribute defined, because mySpan.class is not defined in the Javascript object for a span element. You have to use mySpan.setAttribute('class', 'warning').
然而,第二个细微差别是使用mySpan设置Javascript对象的innerHTML属性。setAttribute("innerHTML", someHTML)不会更新元素的内容。我不知道Javascript是如何捕获mySpan的。innerHTML = something,并调用HTML解析器,但在底层有一些神奇的东西。
如果您希望在JavaScript中进行编程访问,您应该始终使用直接的.attribute形式(但请参阅下面的quirksmode链接)。它应该正确地处理不同类型的属性(想想“onload”)。
使用getAttribute/setAttribute当你希望处理DOM,因为它是(例如,文字文本)。不同的浏览器会混淆这两者。参见怪癖模式:属性(在)兼容性。
来自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
这看起来像是使用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);
}