灵感来自 this question处理类似的情况,我想知道是否有人可以解释当 id 属性不存在时让 element.id 返回空字符串的决定背后的理由。
如果规范是返回 null
或 undefined
我可以简单地写
var allIds = $('#my-frm input').map(function() { return this.id; }).get();
相反,我必须向选择器添加限定符,如
var allIds = $('#my-frm input[id]').map(function() { return this.id; }).get();
或使用针对上述问题提出的其他解决方案(如果存在,则必须两次获取 id)
var allIds = $('#my-frm input').map(function() { return (this.id) ? this.id : null; }).get();
或者我可以使用 jquery 属性 getter,这似乎没有必要首先将每个元素包装到 jquery 对象中,但我提到它是为了完整性,并表明 jquery 使用 .attr() 方法走向了另一个方向。
var allIds = $('#my-frm input').map(function() { return $(this).attr('id'); }).get();
我很好奇 javascript element.id 行为背后是否有实际原因。
更新:
我终于找到了相关的规范,它定义当前的行为(它没有解释为什么它是这样定义的)
https://www.w3.org/TR/2015/REC-dom-20151119/#element
interface Element : Node {
readonly attribute DOMString? namespaceURI;
readonly attribute DOMString? prefix;
readonly attribute DOMString localName;
readonly attribute DOMString tagName;
attribute DOMString id;
attribute DOMString className;
...
创建的元素具有 id
属性且其值不是空字符串,或者当元素的 id
属性设置为空字符串以外的值时字符串,将元素的 ID 设置为新值。
当元素的 id
属性被删除或设置为空字符串时,取消设置元素的 ID。
一些 IDL 属性被定义为反射(reflect)给定名称的特定内容属性。这意味着在获取时,必须运行这些步骤:
使用内容属性的名称获取上下文对象的属性,并将值作为结果。
如果值为 null,则返回空字符串。
返回值。
在设置时,使用属性名称和给定值为上下文对象设置属性。
id
属性必须反射(reflect)“id
”内容属性。
最佳答案
I'm curious if there is a practical reason behind the javascript element.id behavior.
参见 Element.id
The
Element.id
property represents the element's identifier, reflecting theid
global attribute.
If the spec was to return
null
orundefined
Identifiers are opaque strings. Particular meanings should not be derived from the value of the id attribute.
Note There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
Note An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragment identifiers, as a way to target an element when scripting, and as a way to style a specific element from CSS.
It's funny how the result is kind of opposite of the intent. Because I want to avoid calling a separate method to check for the existence of
id
将 $.map()
替换为 .map()
, Array.prototype.filter()
参数为 Boolean
.get()
返回非空字符串的 id
var allIds = $.map($("input"), function(el) {
return el.id
}).filter(Boolean);
jsfiddle https://jsfiddle.net/gqvfuzqr/
关于javascript - 为什么没有 id 的元素上的 element.id 不返回 undefined 或 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34985130/