使用JQuery替换文本

问题描述:

我正在尝试使用JQuery替换文本.但它会替换为重复的文本.

Hi I am trying to replace a text using JQuery. but it's replacing with duplicate text.

我尝试了以下代码:

HTML代码

<a class="text_div">
    This div contains some text.
</a>
<br>
<a class="text_div">
    This div contains some text.
</a>
<br>
<a class="text_div">
    This div contains some text.
</a>

jQuery代码

$(document).ready(function(){
    var text = $('[class="text_div"]').text();
  var new_text = text.replace("contains", "hello everyone");  
  $('[class="text_div"]').text(new_text);
});

结果OUT投放

This div hello everyone some text. This div contains some text. This div contains some text. 
This div hello everyone some text. This div contains some text. This div contains some text. 
This div hello everyone some text. This div contains some text. This div contains some text.

期望投放

This div hello everyone some text.
This div hello everyone some text. 
This div hello everyone some text.

尝试这样

  $('.text_div').each(function(x){
    var new_text = $(this).text().replace("contains", "hello everyone"); 
    $(this).text(new_text);
  })

针对评论中的问题,尝试:

for the question in the comment try:

<a class="text_div">
    This div contains - some text.
</a>
  $('.text_div').each(function(x){
        var new_text = $(this).text().split('-'); 
        $(this).html(new_text[0]+'span style="color:red;font:bold;">'+new_text[1]+'</span>');
      })