gpt4 book ai didi

javascript - querySelector 中哪些字符需要转义?

转载 作者:可可西里 更新时间:2023-11-01 02:39:34 31 4
gpt4 key购买 nike

根据此处的文档:https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector#Notes

它说在做querySelector时需要转义一些字符:

To match ID or selectors that do not follow the CSS syntax (by using a colon or space inappropriately for example), you must escape the character with a back slash. As the backslash is 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):

我希望编写一个函数来对字符串进行转义,但需要知道首先需要转义哪些字符。

谢谢

最佳答案

更新的答案:

在下面的评论中你说:

The thing is Im making a firefox addon Im doing is identifying items by the attribute in label (cuz class is same for all items). and so querySelector('[label="blah blah blah"]') and the user can edit the label, so thats where the problem comes in, users can make it anything.

啊,这改变了一切。一组完全不同的规则适用于属性选择器中的操作数。当你使用 " 来包围操作数时,我认为你只需要用反斜杠转义 " (当然,用反斜杠转义任何反斜杠),例如带有文本 testing "one "二三 将是 [label="testing\"one\"two three"]。因此,从包含目标标签的变量开始,我们会将所有 " 字符替换为 \" 并将所有 \ 字符替换为 \\:

var div = document.querySelector('[label="' + theLabel.replace(/["\\]/g, '\\$&') + '"]');

完整示例:Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Escaping attributes</title>
</head>
<body>
<div label='testing "one" \two three'>This should turn green</div>
<script>
(function() {
var label = 'testing "one" \\two three';
var div = document.querySelector('[label="' + label.replace(/["\\]/g, '\\$&') + '"]');
div.style.color = "green";
})();
</script>
</body>
</html>

原答案:

the CSS specification 中的完整详细信息;例如,ID 和类选择器中哪些字符需要转义的详细信息是 here :

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

现在,关于 querySelector/querySelectorAll 的事情是,因为它们采用字符串,并且反斜杠在字符串文字中很特殊,所以您必须使用 两个 字符串文字中的反斜杠,以便在您的 CSS 选择器中有 一个 反斜杠。因此,对于引用中的最后一个示例,假设您想将其用作类选择器。你必须这样做:

var list = document.querySelectorAll(".B\\26 W\\3F");

...将选择器 .B\26 W\3F 传递给选择器引擎。 Live Example | Live Source

关于javascript - querySelector 中哪些字符需要转义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22830519/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com