【问题标题】:How to fix an ID which isn't accepted as a query selector? [duplicate]如何修复不被接受为查询选择器的 ID? [复制]
【发布时间】:2016-12-24 13:11:49
【问题描述】:

以下代码返回控制台错误:

“未捕获的 SyntaxError: 无法在 'Document' 上执行 'querySelector': '#57acafcbdb4bc607922b834f' 不是有效的选择器。”

HTML5 不应该接受以数字开头的 ID 吗?对于需要这种类型的 ID 的情况,是否有解决方法?

<!DOCTYPE html>
<html>
<body>

<h2 id="57acafcbdb4bc607922b834f">A heading with class="example"</h2>
<p>A paragraph with class="example".</p>

<p>Click the button to add a background color to the first element in the document with class="example".</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    document.querySelector("#57acafcbdb4bc607922b834f").style.backgroundColor = "red";
}
</script>

</body>
</html>

【问题讨论】:

  • 如果你可以控制服务器端的 html 生成,你可以生成像 "hash_" + hashValue 这样的 id,然后你的标记看起来像 `id="hash_57acafcbdb4bc607922b834f" 然后你可以选择querySelector("#hash_57acafcbdb4bc607922b834f").

标签: javascript html css


【解决方案1】:

以数字开头的 ID 在 HTML 5 中确实有效,但 #57acafcbdb4bc607922b834f 不是有效的 CSS 选择器,document.querySelector() 使用 CSS 选择器。

你可以使用属性选择器来代替:

document.querySelector('[id="57acafcbdb4bc607922b834f"]')

或者你可以使用document.getElementById():

document.getElementById('57acafcbdb4bc607922b834f')

查看这段代码sn-p:

console.log(document.querySelector('[id="57acafcbdb4bc607922b834f"]'))
console.log(document.getElementById('57acafcbdb4bc607922b834f'))
&lt;div id="57acafcbdb4bc607922b834f"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    // Escape the first digit with its unicode value in hex
    document.querySelector('#\\35 1').style.color = 'green' 
    
    // Or use getElementById 
    document.getElementById('52').style.color = 'red'
    <div id="51"> Element 51, should be green </div> 
    <div id="52"> Element 52, should be red

    来源:https://mothereff.in/css-escapes

    【讨论】:

    • 代码后面的空格是怎么回事?
    • 结束转义码以消除与\u0351的歧义,\u0351也是unicode字符
    • HTML 和 JavaScript 使用 Unicode,而不是 ASCII。
    • ascii 是 unicode 的一个子集,但是是的,你是对的。编辑修复,谢谢
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2021-09-08
    • 2016-05-02
    相关资源
    最近更新 更多