2013-01-09 25 views
1

可能重複:
jQuery find and replace string找到內容爲div jQuery的一些文字

這是我的html:

<div class="dt_lft">There is an error</div> 

我需要找到DIV是否有文字error,並用success使用類名取代該文本。這個怎麼做?

+6

首先必須在這裏發帖後嘗試自己,這是規則 – ShibinRagh

+1

「有成功」? :) –

+2

這裏有一個類似的問題http://stackoverflow.com/questions/5115152/jquery-find-and-replace-string。 – uchamp

回答

2
$("div.dt_lft:contains('error')").text(function(i,text){ 
    return text.replace('error', 'success'); 
}); 

http://jsfiddle.net/ztCcB/1/


$("div.dt_lft:contains('error')")返回所有的div包含詞errordt_lft類,你可以閱讀更多關於jQuery的contains selector。與jQuery .text()您可以編寫功能:

$(object).text(function(index,CurrentContent){ 
    //somecode here 
} 

在其他地方,如果你的對象包含文字error很多次,你可以這樣做:

text.split('error').join('success'); 

如果你不想使用正則表達式。

+1

我喜歡這個被接受的事實,儘管它與我的很相似...哦,我喜歡這樣! – BenM

+1

它正在工作。謝謝。 –

+0

@BenM它是我,你的評論upvoter:D – F0G

0

試試這個

var m=$(".dt_lft").html(); 
m=m.replace("error","success"); 
$(".dt_lft").html(m); 
8

您可以使用:contains()選擇:如果這是可能的字符串error時間會比在文本再次

$("div.dt_lft:contains('error')").text(function(i, text) { 
    return text.replace('error', 'success'); 
}); 

,你需要使用正規辦理:

$("div.dt_lft:contains('error')").text(function(i, text) { 
    return text.replace(new RegExp('error', 'g'), 'success'); 
}); 
0

試試這個,

if($("div.dt_lft:contains('error')")){ 
    $('.dt_lft').replace('error','success'); 
}