以下代码返回控制台错误:如何修复未被接受为查询选择器的ID?
“未捕获的SyntaxError:未能执行‘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控件,您可以生成ID,如“hash_” +散列值,然后您的标记看起来像'ID = “hash_57acafcbdb4bc607922b834f”然后您可以使用querySelector(“#hash_57acafcbdb4bc607922b834f”)进行选择。 – Chris