直接添加属性作为元素属性

时间:2014-02-14 13:49:51

标签: javascript html

以下是我更改现有属性值的方法:

element.attributeName = "value"


但是,使用上述方法创建 new 属性是否可以?

注意:

  1. 仅限JavaScript。
  2. 请提供相关文件。
  3. 我不需要支持旧浏览器。

2 个答案:

答案 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)

以下是您的回答:add new attribute

<强>编辑:

纯JavaScript:

1st 2nd