在元素中使用特定类型的 id 时,我遇到了 document.querySelector()
函数的错误。当 id 为 canvas-=
时,querySelector 将失败并出现错误 -> 无法在“Document”上执行“querySelector”:“#canvas-=”不是有效的选择器。
但是当我使用 document.getElementById()
时,它可以工作。我可以在 querySelector 中使用 "[id='canvas-=']"
但为什么它在 document.querySelector("#canvas-=")
上失败?
document.querySelector("#canvas-=")
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p id="canvas-=">This is a paragraph.</p>
<script>
const elem = document.querySelector("#canvas-=");
console.log(elem.innerHTML);
</script>
</body>
</html>
document.getElementById("canvas-=")
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p id="canvas-=">This is a paragraph.</p>
<script>
const elem = document.getElementById("canvas-=");
console.log(elem.innerHTML);
</script>
</body>
</html>
但是如果我从 id 中删除 =
一切都会正常。以任何方式插入它都不起作用。 ==-
、=-
、-=
所有这些都会给出错误。那么这里的 =
符号有什么问题,为什么第二种方法可以工作,而第一个方法却不行?
最佳答案
So what is wrong with the
=
symbol in thisdocument.querySelector("#canvas-=")
如 querySelector
docs 中所述:
To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("
\
"). As the backslash is also an escape character in JavaScript, if you are entering a literal string, you must escape it twice (once for the JavaScript string, and another time forquerySelector()
):
工作演示:
const elem = document.querySelector("#canvas-\\=");
console.log(elem.innerHTML);
<h1>This is a Heading</h1>
<p id="canvas-=">This is a paragraph.</p>
why does the second method works but the first doesn't?
发生这种情况是因为 getElementById()
不使用相同的 CSS3 选择器来查询 DOM,因此我们可以毫无问题地使用特殊字符。
工作演示:
const elem = document.getElementById("canvas-=");
console.log(elem.innerHTML);
const elem2 = document.getElementById("canvas.foo");
console.log(elem2.innerHTML);
<h1>This is a Heading</h1>
<p id="canvas-=">This is a paragraph.</p>
<p id="canvas.foo">This is a 2nd paragraph.</p>
关于javascript - document.querySelector 不适用于 id 内的 "="符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997439/