我正在尝试搜索并替换正文中具有相同名称的文本 但它是部分工作,一些文本正在被替换,但后来一些旧文本仍然出现,不太确定发生了什么。
$(document).ready(function() {
$('*').each(function(){
if($(this).children().length == 0)
$(this).text($(this).text().replace("old text", "replace with new text"));
});
});
非常感谢
感谢
答案 0 :(得分:5)
使用:contains
伪类选择器查找包含该文本的任何元素,然后从那里替换。
$(":contains('old text')").each(function(){
$(this).text($(this).text().replace('old text', 'new text'));
});
如果您知道要定位的元素列表,则另一种解决方案是首先找到这些元素,然后使用:contains过滤它们。
$('div, p, a, span').filter(":contains('old text')").each(function(){
$(this).text($(this).text().replace('old text', 'new text'));
});