我有一份具有以下结构的文件:
<div id="notice" class="box generalbox">
<p>
This is some text.
</p>
</div>
我想替换一些&#34;一些&#34;用&#34;我的&#34;使用jQuery。
我该怎么做?
我试过了:
$("#notice").text().replace("some", "My");
但那没有用......
更新: 感谢您的所有回复。我使用这个解决方案来实现这个目的:
$("#notice p").text($("#notice p").text().replace("some", "My"));
答案 0 :(得分:9)
您需要定位p
内的#notice
标记:
$("#notice p").text(function(i, text) {
return text.replace("some", "My");
});
答案 1 :(得分:8)
阅读http://api.jquery.com/text/#text-functionindex--text
$("#notice p").text(function (_, ctx) {
return ctx.replace("some", "My");
});
或
$("#notice p").text($("#notice p").text().replace("some", "My"));
或
var p_tag = $("#notice p");
p_tag.text(p_tag.text().replace("some", "My"));
答案 2 :(得分: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);
此函数将保留指定元素中存在的任何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>
并产生以下输出:
<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>
答案 3 :(得分:2)
var text = $("#notice p").text()
text = text.replace("some", "My");
$("#notice p").text(text);
答案 4 :(得分:1)
去试试这个解决方案:
newtext = $("#notice p").text().replace("some", "My");
$("#notice p").text(newtext);
答案 5 :(得分:1)
试试这个,确定你会得到你的结果。
$("#notice p").text(function(i, text) {
return text.replace("some", "My");
});
答案 6 :(得分:0)
试试这个
$('#notice').html().replace("some", "my");
答案 7 :(得分:0)
Salmans的答案很有效,但如果一个段落中有超过1个单词,则不会被替换。所以请改用: (使用全局匹配的正则表达式)
function replaceNodeText() {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.replace(replaceNodeText.regex, replaceNodeText.replace);
} else {
$(this).contents().each(replaceNodeText);
}
}
replaceNodeText.regex = /some/g;
replaceNodeText.replace = "my";
$("#notice").contents().each(replaceNodeText);
或者使用它:
(我刚刚将.replace(x,y)更改为.split(x).join(y),这比replace()更快,请参阅here)
function replaceNodeText() {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.split(replaceNodeText.find).join(replaceNodeText.replace);
} else {
$(this).contents().each(replaceNodeText);
}
}
replaceNodeText.find = "some";
replaceNodeText.replace = "my";
$("#notice").contents().each(replaceNodeText);