使用jquery替换<div>中的<p>中的单词

use*_*124 5 html jquery html5 text replace

我有一个具有以下结构的文档:

<div id="notice" class="box generalbox">
<p>
This is some text.
</p>
</div>
Run Code Online (Sandbox Code Playgroud)

我想使用jQuery将单词"some"替换为"My".

我该怎么做呢?

我试过了:

$("#notice").text().replace("some", "My");
Run Code Online (Sandbox Code Playgroud)

但那没有用......

更新:感谢您的所有回复.我用这个解决方案让它工作:

$("#notice p").text($("#notice p").text().replace("some", "My"));
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 9

您需要在以下内容中定位p标记#notice:

$("#notice p").text(function(i, text) {
    return text.replace("some", "My");
});
Run Code Online (Sandbox Code Playgroud)

  • @nnnnnn谢谢 - 忘记了`return` (3认同)
  • 别客气.如果没有它,你会得到很多赞成,所以想象一下你会得到多少... (2认同)

Tus*_*har 8

阅读http://api.jquery.com/text/#text-functionindex--text

$("#notice p").text(function (_, ctx) {
    return ctx.replace("some", "My");
});
Run Code Online (Sandbox Code Playgroud)

要么

$("#notice p").text($("#notice p").text().replace("some", "My"));
Run Code Online (Sandbox Code Playgroud)

要么

var  p_tag = $("#notice p");
p_tag.text(p_tag.text().replace("some", "My"));
Run Code Online (Sandbox Code Playgroud)


Sal*_*n A 5

这是一种矫枉过正,但无论如何:

function replaceNodeText() {
    if (this.nodeType === 3) {
        this.nodeValue = this.nodeValue.replace(replaceNodeText.find, replaceNodeText.replace);
    } else {
        $(this).contents().each(replaceNodeText);
    }
}
replaceNodeText.find = "some";
replaceNodeText.replace = "my";
$("#notice").contents().each(replaceNodeText);
Run Code Online (Sandbox Code Playgroud)

此函数将保留指定元素中存在的任何html.例如,它将适用于此HTML:

<div id="notice" class="box generalbox">
    <p>This is<br>some text.</p>
    <p>This is so<br>me text.</p>
    <p>This is <b>some</b> text.</p>
</div>
Run Code Online (Sandbox Code Playgroud)

并产生以下输出:

<div id="notice" class="box generalbox">
    <p>This is<br>my text.</p>
    <p>This is so<br>me text.</p>
    <p>This is <b>my</b> text.</p>
</div>
Run Code Online (Sandbox Code Playgroud)

在这里演示