jQuery 如果 div 包含此文本,则替换该部分文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11324559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:28:54  来源:igfitidea点击:

jQuery if div contains this text, replace that part of the text

jquerytextreplacecontains

提问by Daniel

Like the title says, I want to replace a specific part of the text in a div.

正如标题所说,我想替换 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.

例如,我只想用“大家好”替换“包含”。我找不到解决方案。

回答by James Allardice

You can use the textmethod and pass a function that returns the modified text, using the native String.prototype.replacemethod to perform the replacement:

您可以使用该text方法并传递一个返回修改文本的函数,使用本机String.prototype.replace方法执行替换:

?$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});?????

Here's a working example.

这是一个工作示例

回答by grc

If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:

如果可能,您可以将要替换的单词包装在 span 标签中,如下所示:

<div class="text_div">
    This div <span>contains</span> some text.
</div>

You can then easily change its contents with jQuery:

然后,您可以使用 jQuery 轻松更改其内容:

$('.text_div > span').text('hello everyone');

If you can't wrap it in a span tag, you could use regular expressions.

如果您不能将其包装在 span 标签中,则可以使用正则表达式。

回答by Fabrizio Calderan

var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));

回答by hfarazm

Very simple just use this code, it will preserve the HTML, while removing unwrapped text only:

非常简单,只需使用此代码,它将保留 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");  

    });
});

Here is full example: https://blog.hfarazm.com/remove-unwrapped-text-jquery/

这是完整示例:https: //blog.hfarazm.com/remove-unwrapped-text-jquery/

回答by z33m

You can use the contains selectorto search for elements containing a specific text

您可以使用contains 选择器来搜索包含特定文本的元素

var elem = $('div.text_div:contains("This div contains some text")')?;
elem.text(elem.text().replace("contains", "Hello everyone"));

??????????????????????????????????????????

?????????????????????????????????????????????