问题
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