我什么时候需要逃避元字符? (jQuery 选择器)
根据 jQuery 文档,当选择器字符串中出现的元字符作为文字出现时,我需要对其进行转义。然而,我找不到很多关于何时和何时不转义选择器的具体示例。因此,何时何地我不需要转义元字符,当它们被解释为文字时,在:
属性选择器中?即
$("[attr=value]")
ID 选择器?即
$("#id")
类选择器?即
$(".class");
,有没有办法编写一个函数来替换选择器字符串中的元字符,同时仍然保留起始字符?即:
// replace all meta chars, preserving the id selection?
$("#id.rest$of*string")
// replace all meta chars, preserving the attribute selection?
// going back to my previous question, do I even need to escape the metachars in this situation?
$("[attr=blah.dee#foo*yay]")
我问这个问题的原因是因为我正在使用的网站恰好有一些非常讨厌的选择器。而且我无法控制该网站,因此我无法更改选择器以更好地使用。
谢谢!!
According to the jQuery docs, I need to escape metacharacters that occur in my selector strings, when they occur as a literal. However, I couldn't find very many specific examples of when and when not to escape selectors. So when and when don't I need to escape metacharacters, when they are to be interpreted as a literal, in:
Attribute selectors? ie
$("[attr=value]")
Id selectors? ie
$("#id")
Class selectors? ie
$(".class");
And, is there a way to write a function that replaces metachars in selector strings, while still preserving the beginning character? ie:
// replace all meta chars, preserving the id selection?
$("#id.rest$of*string")
// replace all meta chars, preserving the attribute selection?
// going back to my previous question, do I even need to escape the metachars in this situation?
$("[attr=blah.dee#foo*yay]")
The reason I ask this question, is because I'm working with a website that happens to have some really nasty selectors. And I don't have control over the website, so I can't go change the selectors to be nicer to work with.
THANKS!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 jQuery 文档:
所有这些都必须转义:
前四个是显而易见的,下面是 XML 中第五个元素名称的示例。例如,
如果您必须选择全部, 则仍然有效。
user.name
的元素,则必须对.
进行转义From the jQuery docs:
All of these must be escaped:
The first four are obvious, and here's an example for the fifth. Element names in XML can contain a "." character for instance and still be valid.
If you had to select all elements of
user.name
, then that.
must be escaped我不会公然窃取别人的答案,而是向您指出: jQuery 选择器值转义,其中详细介绍了jQuery的选择器解析方法。
简短的回答:您可能会遇到麻烦,因为 jQuery 的选择器解析器不是 100% 符合标准。根据链接答案中的建议,您可以通过调用常规 DOM 方法 (
document.getElementById()
) 来解决此问题,该方法将与有趣的选择器一起使用,然后将原始 DOM 元素传递给jQuery 选择器。Rather than blatantly stealing someone else's answer, I'll point you to it: jQuery selector value escaping, where jQuery's selector parsing method is described in detail.
The short answer: you may be in trouble since jQuery's selector parser is not 100% standards-complaint. Per the suggestion in the linked answer, you may be able to workaround by calling the regular DOM methods (
document.getElementById()
), which will work with funny selectors, and then pass the raw DOM element to the jQuery selector.