以下代碼返回控制檯錯誤:如何修復未被接受爲查詢選擇器的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