以下是我更改现有属性值的方法:
element.attributeName = "value"
但是,使用上述方法创建 new 属性是否可以?
注意:
答案 0 :(得分:2)
element.attribute = x
适用于W3C定义的属性或元素上已指定的节点属性。
这是在MDN上读取的确切工作:
if attributeName is a W3C defined attribute and an attribute node for the element (e.g., id),
that Attribute Node gets assigned the value of x
if attributeName isn't a W3C defined attribute or an attribute node for the element,
the element's (JavaScript object) attributeName property is assigned the value of x
请参阅此页面上的语法部分:https://developer.mozilla.org/en-US/docs/Web/API/Node.attributes
<强>实施例强>
采用以下DOM元素
<div data-goals="3" id="container"></div>
您可以通过
修改data-goals
document.getElementById('container').dataGoals = '4';
如果这些属性由W3C定义,您还可以添加新属性,例如: title
document.getElementById('container').title = 'This is a title';
但是你不应该期望能够设置一个未由W3C定义的新属性
document.getElementById('container').myOwnAttribute = 'something';
答案 1 :(得分:-2)