2016-08-17 55 views
-1

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

如果你有在服務器端生成HTML控件,您可以生成ID,如「hash_」 +散列值,然後您的標記看起來像'ID = 「hash_57acafcbdb4bc607922b834f」然後您可以使用querySelector(「#hash_57acafcbdb4bc607922b834f」)進行選擇。 – Chris

回答

2

的ID與數字開頭的是HTML 5的確有效,但#57acafcbdb4bc607922b834f不是有效的CSS選擇器,document.querySelector()使用CSS選擇器。

您可以使用屬性選擇器來代替:

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

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

document.getElementById('57acafcbdb4bc607922b834f') 

看到這個代碼片段:

console.log(document.querySelector('[id="57acafcbdb4bc607922b834f"]')) 
 
console.log(document.getElementById('57acafcbdb4bc607922b834f'))
<div id="57acafcbdb4bc607922b834f"></div>

1

// 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

+0

代碼之後的空間是什麼? – Musa

+1

它結束轉義代碼以從\ u0351中消除歧義,這也是一個unicode字符 – user3080953

+1

HTML和JavaScript使用Unicode,而不是ASCII。 –