5

我正在尝试搜索并替换同一个单词的所有实例,使用 .contains () 不区分大小写,但它似乎不起作用并且区分大小写。这是我现在拥有的代码:

<p>some text</p>
<p>Some Text</p>
<p>Some TEXT</p>


jQuery.expr[':'].Contains = function(a, i, m) {
         return jQuery(a).text().toUpperCase()
             .indexOf(m[3].toUpperCase()) >= 0;
       };
       jQuery.expr[':'].contains = function(a, i, m) {
         return jQuery(a).text().toUpperCase()
             .indexOf(m[3].toUpperCase()) >= 0;
       };


        $('p').filter(":contains('some text')").each(function(){
            $(this).text($(this).text().replace("some text", "replace with new text"));
        });

这只会更改第一个文本,因为同样的情况,您可以在此处查看 js fiddle 上的示例 http://jsfiddle.net/ka82V/

4

4 回答 4

2

它实际上是区分大小写的“替换”。改用正则表达式:

text().replace(/some text/i, "replace with new text"));

演示 http://jsfiddle.net/ka82V/1/

于 2012-05-07T21:06:34.150 回答
2

你包含看起来不错。尝试如下,因为使用的目的.filter是链接

演示

jQuery.expr[':'].containsCI = function(a, i, m) {
    return jQuery(a)
        .text()
        .toUpperCase()
        .indexOf(m[3].toUpperCase()) >= 0;
};

$('p').filter(":containsCI('some text')").text(function() {
    return $(this).text().replace(/some text/i, "replace with new text");
});
于 2012-05-07T21:06:55.393 回答
1

问题不在于原始匹配,而在于您如何替换。即使确实匹配,替换也没有做任何事情,因为它的“某些文本”参数与其他大小写变体不匹配。

但是,我认为:contains像这样覆盖 jQuery 的选择器并不是一个好主意。使用基于函数的过滤器的代码更少,并且 jQuery 也保持不变。

参见工作示例:http: //jsfiddle.net/Y6bhS/1/

$('p').filter(function() {
    return /some text/i.test( $(this).text() );
}).each(function(){
    $(this).text($(this).text().replace(/some text/i, "replace with new text"));
});
于 2012-05-07T21:10:29.287 回答
1
jQuery.expr[':'].Contains = function(a, i, m) {
    return new RegExp(m[3], 'ig').test(jQuery(a).text());  // case insensitive replace
};
jQuery.expr[':'].contains = function(a, i, m) {
    return new RegExp(m[3], 'ig').test(jQuery(a).text());  // case insensitive replace
};

$('p').filter(":contains('some text')").each(function() {
     $(this).text($(this).text().replace( new RegExp($(this).text(), 'i'),"replace with new text"));
});
于 2012-05-07T21:13:15.093 回答