2013-02-27 84 views
1

的jsfiddle:http://jsfiddle.net/WM6wG/替换文本包含(比赛)

我想更换一个div文本,但似乎无法弄清楚,为什么它不工作。

HTML:

<div class="text">abc</div> 
<div class="text">foo</div> 
<div class="text">bar</div> 

的jQuery:

var match = 'abc'; 
if ($('div.text:contains(match)')) { 
    $('div.text').html(function(){ 
     $(this).replaceText(match, 'xyz'); 
    } 
} 

理想预期的输出应该是:xyz foo bar但它仍然abc foo bar,我究竟做错了什么?

+2

' 'div.text:包含(' +匹配+ ')''只要你有'replaceText'包含的插件 – 2013-02-27 17:39:39

回答

7

有你的代码的几个问题:

  1. 您正在搜索“匹配”,而不是变量match的价值。

  2. 您的if声明是毫无意义的,因为您在下一行上有一个新的选择器div.text。因此,如果其中一个元素匹配,那么您的代码无论如何都会针对所有匹配元素运行此操作。

  3. 你的html()方法没有返回任何东西。

  4. replaceText()不是标准功能。除非这是一个自定义函数,你发了,或者你使用的是replaceText() plugin,与replace()


var match = 'abc'; 
$("div.text:contains(" + match + ")").each(function(){ 
    var $this = $(this); 
    $this.html(function(){ 
     return $this.html().replace(match, "xyz"); 
    }); 
}); 

现场演示替换:http://jsfiddle.net/wh7xn/


如果有多个您想要替换的“abc”实例,请使用RegEx:

var match = 'abc'; 
var re = new RegExp(match,"g"); 
$("div.text:contains(" + match + ")").each(function(){ 
    var $this = $(this); 
    $this.html(function(){ 
     return $this.html().replace(re, "xyz"); 
    }); 
}); 

现场演示http://jsfiddle.net/wh7xn/2/

+0

在同一个div中包含多个'abc'实例怎么办? – 2013-02-27 17:58:33

+1

@OP使用正则表达式http://jsfiddle.net/wh7xn/2/ – Curt 2013-02-27 18:03:01

2

当你做$('div.text:contains(match)')你正在寻找一个包含字符串'match'的div。

你可以做这样的:$('div.text:contains(' + match + ')')

只是要小心的是,可变匹配不包含任何有意义的东西到jQuery选择,如)

1

updated fiddle

$(document).ready(function(){ 
    var match = 'abc'; 
    if ($('div.text:contains('+match+')')) { 
     $('div.text').html(function(){ 
      $(this).replaceText(match, 'xyz'); 
     }); 
    } 
}); 

两件事情!

  1. '('+match+')'
  2. 你忘了一个括号中的功能后,关闭HTML调用。
  3. 的功能replaceText JS文件(!@Jasen谢谢)
+1

3. jquery.ba-replacetext.js – Jasen 2013-02-27 17:47:45

+0

@Jasen真的! – 2013-02-27 17:49:04

1

这似乎做这一切在同一行(不包括您的VAR声明):

var match = 'abc'; 
$('div.text:contains(' + match + ')').text($('div.text:contains(' + match + ')').text().replace(match, 'xyz')); 

jsFiddle example

如果需要声明,并且replace而不是replaceText

如果你有多个匹配,使用:

var match = 'abc'; 
$('div.text:contains(' + match + ')').each(function() { 
    $(this).text($(this).text().replace(match, 'xyz')); 
}); 

jsFiddle example

+0

在同一个div中包含多个'abc'实例呢? – 2013-02-27 17:58:58