2011-06-17 82 views
3

我想知道如何去查找和替换div中的某些文本,但我想查找并替换该文本的第二个出现。例如:“您刚刚添加了一个项目,请删除此项目”,因此我想找到第二个“项目”并将其替换为我选择的任何文本。jQuery查找并替换第二个

JS:

var compareCount = $('.compareWidget').find('.compareItem').length; 

if (compareCount >= 2) { 
    $('.message').find('.count').text(compareCount); 
    $('message').html().replace('item', 'items'); 
} 

$('.message').slideDown("Fast"); 

setTimeout(function() { 
    $('.message').slideUp("Fast"); 
}, 5000); 

HTML:

<div id="alertMessage"> 
    <div class="message"> 
     <span>You just added a item to compare, you currently have <span class="count">1</span> item to compare</span> 
    </div> 
</div> 
+0

你可能想要使用正则表达式并获得第二个匹配。 – aepheus

+2

它会是一个动态的字符串或总是“项目”? –

+1

它总是会成为这个例子的“项目” – Lawrence

回答

2

“您目前有1项比较” 要打开项目的项目?

你可以用正则表达式来做到,或者你可以把它包装到一个元素中并抓住它。

<span class="count">1</span> <span class="type">item</span> to compare</span> 

$('.message').find('.type').text("items"); 
2

使用正则表达式,你可以

function replaceMatch(originalString, searchFor , replaceWith, matchNumber) 
{ 
    var match = 0; 
    return originalString.replace(searchFor, function(found){ 
        match++; 
        return (match===matchNumber)?replaceWith:found; 
        },'g'); 
} 

,并调用它像

var msg = $('.message'); 
msg.html(replaceMatch(msg.html(), 'item', 'items', 2)); 

演示http://jsfiddle.net/gaby/crhvA/