jQuery找到并替换第二个

我想知道如何在div中查找和替换一些文本,但我想找到并替换该文本的第二次出现。 例如:“你刚刚添加了一个项目,请删除此项目”,所以我想找到第二个“项目”并用我选择的任何文本替换它。

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:

 
You just added a item to compare, you currently have 1 item to compare

“你目前有1项要比较”你想把物品变成物品吗?

您可以使用正则表达式执行此操作,也可以将其包装到元素中并抓住它。

 1 item to compare 

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

使用正则表达式即可

 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/