gpt4 book ai didi

javascript - 使用 JQuery 替换文本

转载 作者:太空宇宙 更新时间:2023-11-04 13:34:33 25 4
gpt4 key购买 nike

您好,我正在尝试使用 JQuery 替换文本。但它正在替换为重复的文本。

我试过下面的代码:

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);
});

结果输出

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);
})

对于评论中的问题尝试:

<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>');
})

关于javascript - 使用 JQuery 替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38052211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com