简体   繁体   English

如何在jQuery的:contains选择器中转义?

[英]How do I escape parenthesis in jQuery's :contains selector?

I've tried to search for a user-agent string in a table using jQuery. 我试图使用jQuery在表中搜索用户代理字符串。 If I search like this it is not found: 如果我这样搜索,则找不到:

jQuery("table.make-html-table
td:contains('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')")
.css("background","yellow");

If I search like this - slashes before \\( - then it give me an error: 如果我这样搜索-在\\(之前加斜杠--则会给我一个错误:

jQuery("table.make-html-table
td:contains('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')")
.css("background","yellow");

Error: 错误:

"Syntax error, unrecognized expression: (comp...

How can I properly escape that string so that I can search for cells that contain it with jQuery? 如何正确转义该字符串,以便可以用jQuery搜索包含该字符串的单元格?

The relevant part in sizzle is 嘶嘶声的相关部分是

PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/

which makes me think there is no way. 这让我觉得没有办法。 Looks like it only accepts arguments that contain no parenthesis at all, or only one level thereof like :contains("(foo)") . 看起来它仅接受根本不包含括号的参数,或者仅接受其一个级别的参数,例如:contains("(foo)") An obvious improvement would be accept anything if an argument is quoted, hope this will be fixed soon. 如果引用一个引号,则可以接受任何内容,这是一个明显的改进,希望可以尽快解决。

For the time being, a workaround would be to write a selector that would accept escaped arguments, for example: 目前,一种解决方法是编写一个接受转义参数的选择器,例如:

$.extend($.expr[':'], {
    containsEscaped: function (el, index, m) {  
        var s = unescape(m[3]);
        return $(el).text().indexOf(s) >= 0;
    }  
});      

usage: 用法:

var p = $("p:containsEscaped('foo%28bar')");

In action: http://jsfiddle.net/9wWP5/ 实际使用中: http//jsfiddle.net/9wWP5/

Use two slashes: 使用两个斜杠:

 
 
 
 
  
  
  jQuery("table.make-html-table td:contains('Mozilla/4.0 \\\\(compatible; MSIE 6.0; Windows NT 5.1\\\\)')") .css("background","yellow");
 
 
  

Alternate solution: 替代解决方案:

jQuery("table.make-html-table td:contains('Mozilla/4.0'):contains('compatible; MSIE 6.0; Windows NT 5.1')").css('background-color','yellow');

Another solution using textEquals custom selector 使用textEquals自定义选择器的另一种解决方案

jQuery.expr[':'].textEquals = function(a, i, m) {
    return jQuery(a).text() === m[3];
};

...

jQuery("table.make-html-table td:textEquals('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')")
    .css("background","yellow");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM