2013-01-23 61 views
5

我只是碰到这样的事情跌跌撞撞......DOM元素的属性指定了什么属性?

function(element) { 
    ... 
    var attributes = element.attributes; 
    for (var index = 0, length = attributes.length; index < length; index++) { 
    var attribute = attributes[index]; 

    // what is ".specified"? 
    if (attribute.specified) { 
     ... 
    } 
    } 
} 

我在寻找一个DOM元素,元素接口的W3C规范,和我没有看到任何地方specified

http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-745549614

是什么attribute.specified意思?它代表什么?规格在哪里定义?

+0

你在想这个吗? http://www.w3schools.com/jsref/prop_attr_specified.asp – LNendza

+0

是的,这就是我正在谈论的 – Hristo

+1

我不知道它在规格中的定义,但我发现它们的定义非常合适: 如果指定了属性,则指定的属性返回true。 如果属性已创建但尚未附加到元素,则返回true。 否则它返回false。 我相信它正在被贬损的方式。 – LNendza

回答

2

<img src="kittens.jpg">。该属性为src,其值为kittens.jpg。 DOM元素是通用定义。实际属性由正在使用的实际语言指定,例如, XML,HTML等......

指定=该属性具有分配给它的显式值。例如src属性指定的,因为它已经给定的值kittens.jpg,但

<input type="checkbox" checked /> 

检查的属性存在,但没有规定。

+0

编号'specified'只是表示该属性存在于原始HTML中,或者已由脚本使用'setAttribute()'设置。在你的例子中'checked'是**指定的。例如:http://jsfiddle.net/timdown/DM8Tr/1/。规格:http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-637646024 –

+0

嘿蒂姆...你介意创建一个自己的答案与一些更多的细节? – Hristo

-1

不同的浏览器有不同的DOM实现,请注意实现负责此属性,而不是用户。但是,用户可以更改属性的默认值。

对于Chrome 54.0.2840.71,它使每个属性指定为真,无论是否在DOM规范中,无论它是否有价值。例如, 例如,Chrome(版本54)中指定的属性__test始终为true。

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Document</title> 
</head> 
<body> 
    <div __test></div> 
    <script> 
     var div=document.querySelector("div"); 
     var attributes = div.attributes; 
     var attr_test=attributes[0]; 
     attr_test.specified=false;// "specified" is not writable and Setting it silently fails. 
     console.log(attr_test.specified); 
    </script> 
</body> 
</html> 

所以我同意“这是对被剥夺的方式”。

“attribute.specified”在DOM level3中与DOM level2 spec不同。

1.same点

如果此属性是明确给出了实例文档中的值,否则为false。如果应用程序更改了此属性节点的值(即使它最终具有与默认值相同的值),它将被设置为true。

2.Differences
“DOM-2级别”有更复杂的判断条件来决定是否“attribute.specified”是真还是假。
“DOM-Level3的说:”

实现可以处理与其他模式类似的默认值,但应用程序的属性应该使用的Document.normalizeDocument()来保证此信息都是最新的。

搜索specified of type boolean, readonly
https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-637646024
VS
https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-862529273

0

我刚才发现,属性节点的属性specified只针对IE 6-7有意义的信息,因为在IE 6-7 attributes通过特定元素节点返回的所有属性的集合。然后,您可以使用specified来查明集合中的属性是否附加到元素节点。如果元素节点没有指定/定义此属性,它将返回false。在现代浏览器attributes返回的属性集合附着其实元素,这意味着每attribute.specified从收集将在现代浏览器返回true。对于现代浏览器而言,element.hasAttribute(attribute)的工作方式是,element.attributes[attribute].specified适用于IE 6-7。