2016-08-17 24 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。 –