首页 > 解决方案 > 如何理解 document.queryselector 中的转义字符?

问题描述

我在看https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#Escaping_special_characters

我无法理解这一部分:

// "#fooar" (\b is the backspace control character)
console.log('#foo\bar');
 // Does not match anything
document.querySelector('#foo\bar');

console.log('#foo\\bar'); // "#foo\bar"
console.log('#foo\\\\bar'); // "#foo\\bar"
document.querySelector('#foo\\\\bar');
<div id="foo\bar"></div>
<div id="foo:bar"></div>

我是 JavaScript 初学者,不明白为什么 4 个斜杠,我发现了另一个类似的问题,但我不明白答案。

我尝试document.getElementById在“foo\bar”上运行,它可以使用 2 个斜杠,这对我来说很有意义,因为您需要一个额外的反斜杠来转义第一个反斜杠,但是为什么在使用 querySelector 时需要额外的 3 个?

我在这里看过类似的帖子,但答案对我来说并不清楚,我正在寻找一个简单的分解解释,说明这里发生了什么,以及我理解的 getelementbyid 的工作方式(双反斜杠)和 queryselector (它使用4)。

标签: javascriptcsscss-selectors

解决方案


根据 MDN Web Docs,关于litteral Strings

除了常规的可打印字符外,特殊字符还可以使用转义符号进行编码。

  • \\->\

现在,关于方法Document.querySelector

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 for querySelector()):

No such things is required for Document.getElementById (no explanation is given, maybe it's for legacy reason). Now, back to our question:

Consider the process as a two-pass formatting, let's view them backwards:

  1. You need to send to querySelector a backslash. To fit the requirement of querySelector, You need to escape it once : "#foo\\bar".
  2. If you want to represent a backslash in a Javascript String, you need to escape it. Let's escape each backslash; we get "#foo\\\\bar"

推荐阅读