2013-02-27 44 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