Dan*_*iel 75 jquery text replace contains
就像标题所说,我想替换div中文本的特定部分.
结构如下所示:
<div class="text_div">
This div contains some text.
</div>
Run Code Online (Sandbox Code Playgroud)
例如,我想用"hello everyone"替换"contains".我无法找到解决方案.
Jam*_*ice 135
您可以使用该text
方法并传递一个返回已修改文本的函数,使用本机String.prototype.replace
方法执行替换:
?$(".text_div").text(function () {
return $(this).text().replace("contains", "hello everyone");
});?????
Run Code Online (Sandbox Code Playgroud)
这是一个有效的例子.
hfa*_*azm 10
非常简单,只需使用此代码,它将保留 HTML,同时仅删除未包装的文本:
jQuery(function($){
// Replace 'td' with your html tag
$("td").html(function() {
// Replace 'ok' with string you want to change, you can delete 'hello everyone' to remove the text
return $(this).html().replace("ok", "hello everyone");
});
});
Run Code Online (Sandbox Code Playgroud)
这是完整示例:https : //blog.hfarazm.com/remove-unwrapped-text-jquery/
var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));
Run Code Online (Sandbox Code Playgroud)
如果可能,您可以在span标记中包含要替换的单词,如下所示:
<div class="text_div">
This div <span>contains</span> some text.
</div>
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用jQuery轻松更改其内容:
$('.text_div > span').text('hello everyone');
Run Code Online (Sandbox Code Playgroud)
如果无法将其包装在span标记中,则可以使用正则表达式.
归档时间: |
|
查看次数: |
210205 次 |
最近记录: |