jQuery selector problem when using a single parenthesis

家住魔仙堡 提交于 2020-01-04 09:13:38

问题


If I include a single parenthesis in a :contains selector I get an error.

e.g.

$("a:contains('Speed (mph')")

returns the error

Syntax error, unrecognized expression: (mph')

if I add the closing parenthesis at the end, the statement runs fine. however, I need to be able to query where there is often a single parenthesis.

What's going on here and how do I sidestep this?

EDIT

In my actual code the :contains part is passed in as a variable

e.g

var searchText = 'Speed (mph';
var result = $("a:contains('" + searchText  + "')");

回答1:


You should be able to use $("a:contains('Speed \\(mph')")

From http://api.jquery.com/category/selectors/

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors.




回答2:


As from Matthew Flaschen's link, you could use the filter function like this:

    var searchRegex = new RegExp("Speed \\(mph","g");
    var result = $('a').filter(function(i, el) {
        return $(el).text().match(searchRegex);
    });


来源:https://stackoverflow.com/questions/6469993/jquery-selector-problem-when-using-a-single-parenthesis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!