为什么JS代码“var a = document.querySelector('a [data-a = 1]');”引起错误? [英] Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

查看:447
本文介绍了为什么JS代码“var a = document.querySelector('a [data-a = 1]');”引起错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DOM中有一个元素:



< a href =#data-a =1>链接< / a>



我想通过HTML5自定义数据属性获取此元素 data-a 。所以我写了JS代码:



var a = document.querySelector('a [data-a = 1]');



但这个代码不工作,我在浏览器的控制台中出现错误。 (我测试了Chrome和Firefox。)



JS代码 var a = document.querySelector('a [data-a = a]'); 不会导致错误。所以我认为问题是HTML5的JS API document.querySelector 不支持在HTML5自定义数据属性中查找数字值。



这是浏览器实现的问题或者是与 document.querySelector ?相关的HTML5规范的问题?



然后,我在 http://validator.w3.org/ 上测试了以下代码:

 <!DOCTYPE html> 
< meta charset =utf-8>
< title> HTML文档< / title>
< a href =#data-a =1>链接< / a>

已验证。因为这些HTML5代码已验证。我们应该使用HTML5的JS API document.querySelector ,通过它的自定义数据属性来寻找这个锚点元素。但是事实是我得到错误。



HTML5的规范HTML5 JS API document.querySelector 方法无法查找带有数值的HTML5数据自定义属性? (需要HTML5规范来源。)

解决方案

选择器规范


属性值必须是CSS标识符或字符串。


标识符不能以数字开头。字符串必须引用。



1 因此既不是有效的标识符也不是字符串。



使用1(这是一个字符串)。

  var a = document.querySelector('a [data-a =1]'); 


I've an element in the DOM:

<a href="#" data-a="1">Link</a>

I want to get this element via its HTML5 custom data attribute data-a. So I write JS codes:

var a = document.querySelector('a[data-a=1]');

But this code doesn't work and I get an error in browser's console. (I tested Chrome and Firefox.)

JS code var a = document.querySelector('a[data-a=a]'); doesn't cause error. So I think the problem is that HTML5's JS API document.querySelector doesn't support to look for the number value in HTML5 custom data attribute.

Is this a problem of browser implementation bug or a problem of HTML5's spec relevant to document.querySelector?

Then I tested codes below on http://validator.w3.org/:

<!DOCTYPE html>
<meta charset="utf-8">
<title>An HTML Document</title>
<a href="#" data-a="1">Link</a>

They're validated. Since these HTML5 codes are validated. We should can use HTML5's JS API document.querySelector to look for this anchor element via its custom data attribute. But tha fact is that I get error.

Does HTML5's spec to HTML5 JS API document.querySelector say that this method can not look for an HTML5 data custom attribute with a number value? (An HTML5 spec source is wanted.)

解决方案

From the selectors specification:

Attribute values must be CSS identifiers or strings.

Identifiers cannot start with a number. Strings must be quoted.

1 is therefore neither a valid identifier nor a string.

Use "1" (which is a string) instead.

var a = document.querySelector('a[data-a="1"]');

这篇关于为什么JS代码“var a = document.querySelector('a [data-a = 1]');”引起错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆