【发布时间】: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