如何更改 HTML 中 Div 内的 html,而不影响 Jquery 中父 div 内的内部 div。
到目前为止我有这个:
HTML:
<div id="div_to_change">
This is the text
<br>
to be changed
<div id="div_that_shouldnt_change">
text that should not change
</div>
<div id="div_that_shouldnt_change2">
text that should not change
</div>
</div>
JQUERY:
$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("changed text");
唯一的问题是,如果 html 上没有标签,它可以正常工作,但例如在 <br>
之后它不会改变。或<strong>
等等
最佳答案
一种方法:
$('#div_to_change').contents().each(function () {
//select only nodes with type 3 and having a node value to ignore empty lines, format chars etc
if(this.nodeType == 3
&& $.trim(this.nodeValue)
)
{
$(this).replaceWith("changed text")
}
});
<强> Demo
或者仅使用过滤器:
$('#div_to_change').contents().filter(function () {
return (this.nodeType == 3
&& $.trim(this.nodeValue)
)
}).replaceWith("changed text");
<强> Demo
关于javascript - 如何更改 html div 而不影响 JQuery 中的内部 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559532/