當用querySelector()或querySelectorAll()查找類似name="2nd_btn"的元素時,FF,chrome和IE8都會報錯。
FF,chrome報的錯是一樣的,如下所示:
Error: uncaught exception: [Exception... "An invalid or illegal string was specified" code: "12" nsresult: "0x8053000c (NS_ERROR_DOM_SYNTAX_ERR)" location: ".../test/qsa.html Line: 18"]
IE8的報錯提示:行: 18 錯誤: 參數無效。
一尋思,name的值是以數字開頭的,把數字去掉或修改後,就能取到了。
這就告訴我們,一般可自定義標簽的屬性值時,屬性值不能以數字開頭,也不能包含$,^等不常用的字符。
在HTML頁面開始一定要記得聲明<!DOCTYPE>。
測試代碼:
復制代碼 代碼如下:
<!DOCTYPE>
<html>
<head></head>
<body>
<div id="foo">
<a name="warns" href="">This is a sample warning</a>
<a id="3err" href="">This is a sample error</a>
</div>
<div id="bar">
<a name="warns" href="">This is another sample warning</a>
<a name="1err" href="">This is another sample error</a>
</div>
<script>
var a = document.querySelectorAll("[name=warns]")
alert(a.length)//輸出:2
var b = document.querySelector("[id=3err]")
alert(b.tagName)//報錯
var c = document.querySelectorAll("[name=1err]")
alert(c.length)//報錯
</script>
</body>
</html>