jQuery 如果 div 包含此文本,则替换该部分文本 [英] jQuery if div contains this text, replace that part of the text
本文介绍了jQuery 如果 div 包含此文本,则替换该部分文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所说,我想替换 div 中文本的特定部分.
结构如下:
这个 div 包含一些文本.
例如,我只想将包含"替换为大家好".我找不到解决方案.
解决方案
您可以使用text
方法并传递一个返回修改文本的函数,使用本机 String.prototype.replace
方法执行替换:
$(".text_div").text(function () {return $(this).text().replace("contains", "hello大家");});
这是一个工作示例.
Like the title says, I want to replace a specific part of the text in a div.
The structure looks like this:
<div class="text_div">
This div contains some text.
</div>
And I want to replace only "contains" with "hello everyone", for example. I can't find a solution for this.
解决方案
You can use the text
method and pass a function that returns the modified text, using the native String.prototype.replace
method to perform the replacement:
$(".text_div").text(function () {
return $(this).text().replace("contains", "hello everyone");
});
Here's a working example.
这篇关于jQuery 如果 div 包含此文本,则替换该部分文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文