[英]element.setAttribute('prop',value) vs element.prop = value
We have a setAttribute method, for DOM elements. 我们有一个用于DOM元素的setAttribute方法。
https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute
How is it different from using the below? 它与使用下面有什么不同?
domElement.propName = value
Is there any benefit to either approaches ? 两种方法都有任何好处吗?
Thanks. 谢谢。
domElement.setAttribute('propName', obj)
is setting an XML attribute, it will be converted into a string and added to the DOM tag. domElement.setAttribute('propName', obj)
正在设置XML属性,它将被转换为字符串并添加到DOM标记中。
domElement.propName
is setting an expando property, it can be of any type. domElement.propName
正在设置一个expando属性,它可以是任何类型。 It's setting it on the JS object that wraps the DOM object implementation. 它将它设置在包装DOM对象实现的JS对象上。
They do not have the same effect, unless you are dealing with an attribute that is recognized by the parser like src,id,value
. 它们没有相同的效果,除非您正在处理解析器识别的属性,如src,id,value
。 Those properties get copied to the expando property but there are many rabbit holes and cases where it doesn't work reliably (usually when the expando doesn't take a string, like onclick, checked
) 这些属性被复制到expando属性,但是有许多兔子洞和它无法可靠地工作的情况(通常当expando不接受字符串时,如onclick, checked
)
This example shows that they are different. 这个例子表明它们是不同的。
domElement.setAttribute('someProp', 5);
console.log(domElement.someProp); // undefined
domElement.someProp = 10;
console.log(domElement.someProp); // 10
console.log(domElement.getAttribute('someProp')); // "5" -> it's a string
Always using DOM expando properties is less likely to cause trouble. 始终使用DOM expando属性不太可能导致麻烦。 The only case where you want to use setAttribute is when you need to serialize the node (using outerHTML
) and you want that attribute to be reflected in the serialization 您想要使用setAttribute的唯一情况是您需要序列化节点(使用outerHTML
)并且您希望该属性反映在序列化中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.