jQuery选择器值转义 [英] jQuery selector value escaping

查看:129
本文介绍了jQuery选择器值转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉列表,其中包含一系列选项:

I have a dropdown list that contains a series of options:

<select id=SomeDropdown>
  <option value="a'b]&lt;p>">a'b]&lt;p></option>
  <option value="easy">easy</option>
<select>

请注意,选项值/文本包含一些讨厌的东西:

Notice that the option value/text contains some nasty stuff:


  • 单引号

  • 关闭方括号

  • 转义html

我需要删除a'b]< p>选项,但我没有运气写下选择器。既不:

I need to remove the a'b]<p> option but I'm having no luck writing the selector. Neither:

$("#SomeDropdown >option[value='a''b]&lt;p>']");

$("#SomeDropdown >option[value='a\'b]&lt;p>']");

正在返回选项。

什么是使用value =选择符时转义值的正确方法?

What is the correct way to escape values when using the "value=" selector?

推荐答案

我不认为你可以。它应该:

I don't think you can. It should be:

#SomeDropdown >option[value='a\'b]<p>']

这可以作为CSS选择器(在现代浏览器中)。您将自然需要再次转义JavaScript代码:

And this does work as a CSS selector (in modern browsers). Expressed in a JavaScript string literal you would naturally need another round of escaping:

$("#SomeDropdown >option[value='a\\'b]<p>']")

在jQuery中工作,因为它的选择器解析器不符合标准。它使用这个正则表达式来解析部分 [attr = value] 条件:

But this doesn't work in jQuery because its selector parser is not completely standards-compliant. It uses this regex to parse the value part of an [attr=value] condition:

(['"]*)(.*?)\3|)\s*\]

\3是包含开头引号的组,它奇怪地被允许是多个开头的引号,或者根本没有开放的引号。 * *然后可以解析任何字符,包括引号,直到它碰到第一个']'字符,结束匹配。没有规定反斜杠转义CSS特殊字符,所以你不能匹配jQuery中的任意字符串值。

\3 being the group containing the opening quotes, which weirdly are allowed to be multiple opening quotes, or no opening quotes at all. The .*? then can parse any character, including quotes until it hits the first ‘]’ character, ending the match. There is no provision for backslash-escaping CSS special characters, so you can't match an arbitrary string value in jQuery.

(再次,正则表达式解析器输入。)

(Once again, regex parsers lose.)

但好消息你不必依赖于jQuery选择器;你可以使用完美的DOM方法,特别是HTMLSelectElement.options:

But the good news is you don't have to rely on jQuery selectors; there are perfectly good DOM methods you can use, in particular HTMLSelectElement.options:

var select= document.getElementById('SomeDropdown');
for (var i= select.options.length; i-->0;) {
    if (select.options[i].value=="a'b]<p>") {
        // do something with option
}   }

这比要求jQuery花费大量解析和实现你的选择器要简单得多,而且你可以使用你喜欢的任何值字符串,而不用担心转义特殊字符。

This is many times simpler and faster than asking jQuery to laboriously parse and implement your selector, and you can use any value string you like without having to worry about escaping special characters.

这篇关于jQuery选择器值转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆