简体   繁体   English

查询选择器属性值以空字符串开头失败

[英]Query selector attribute value starts with empty string fails

Can anyone explain why the following returns an empty list: 谁能解释以下内容为何返回空列表的原因:

var el = document.createElement('div');
el.dataset.mydata="hello";
document.body.appendChild(el);
document.querySelectorAll('div[data-mydata^=""]');

(If you're wondering why you'd ever do this, the actual code is using a variable as the attribute value in the querySelector. The function it is part of gets called recursively, on the first run the variable is empty.) (如果您想知道为什么要这样做,那么实际的代码就是使用变量作为querySelector中的属性值。它所包含的函数被递归调用,在第一次运行时,该变量为空。)

This happens because substring matching attribute selectors are dumb : 发生这种情况是因为子字符串匹配的属性选择器很笨

[att^=val]

Represents an element with the att attribute whose value begins with the prefix "val". 表示一个具有att属性的元素,其值以前缀“ val”开头。 If "val" is the empty string then the selector does not represent anything. 如果“ val”是空字符串,则选择器不代表任何内容。

(Emphasis mine.) (强调我的。)

All substring selectors are broken by design: When given the empty string, they return nothing (instead of matching all strings). 所有子字符串选择器都被设计破坏:给定空字符串时,它们不返回任何内容(而不是匹配所有字符串)。 I have no idea why, but it's what the selector specification says. 我不知道为什么,但这就是选择器规范所说的。

The best fix is probably to add a check to your code that says if var is empty, use 'div[data-mydata]' instead (ie only check for the presence of the attribute, not its value). 最好的解决方法可能是在代码中添加一个检查,指出如果var为空,请改用'div[data-mydata]' (即仅检查属性是否存在,而不检查其值)。

You should implement a condition that if the value is empty then to use = operator in selector and if value is not empty then use ^= operator. 您应该实现以下条件:如果值为空,则在选择器中使用=运算符;如果值不为空,则使用^=运算符。

Try running following snippet 尝试运行以下代码段

 var el = document.createElement('div'); var value = ""; el.dataset.mydata = value; document.body.appendChild(el); var elements = document.querySelectorAll(`div[data-mydata${value ? "^": ""}=""]`); console.log(elements.length); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM