使用JQuery替换文本 [英] Replace a text using JQuery

查看:75
本文介绍了使用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>');
      })

这篇关于使用JQuery替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆