需要转义jQuery选择器字符串中的特殊字符 [英] Need to escape a special character in a jQuery selector string

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

问题描述

根据选择器文档,您必须逃避 [有双反斜杠等 \\ [

According to the selectors docs, you must escape [ with double backslash, etc \\[.

我有一个选择器是这样创建的(在这个例子中假设 val 属性是某事[4] [2] )。

I have a selector that is created like so (assume val attribute is something[4][2] in this example).

var val = $(this).attr('val');           

$select.find('option[value=' +  val + ']').show();

我可以写一个正则表达式来逃避括号吗?

Can I write a regex to escape the brackets for me?

推荐答案

如果你想要一些适用于任何价值的东西,试试这个:

If you want something that works with any sort of value, try this:

var val = $(this).attr('val').replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, "\\\\$&")

这可以通过转义选择器中列出的所有CSS元字符来实现带有两个反斜杠的jQuery文档页面。

This works by escaping all CSS meta-characters listed on the Selectors page of the jQuery documentation with two backslashes.

请记住,在你的情况下,没有必要像这样做一些棘手的东西。你可以使用过滤器函数用于选择具有给定值的所有选项元素,而不必转义该值,如Mathias Bynens的回答。

Keep in mind that in your situation, there is no need to do something tricky like this. You can use the filter function to select all option elements with a given value without having to escape the value, as described in Mathias Bynens's answer.

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

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