我想从(remove this)
内容中删除div
。我正在使用它,它可以工作,但它也将bar
更改为foo
var replaced = $("div").html().replace(/\(.*\)/g, '');
$("div").html(replaced);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
foo (remove this)
</div>
<div>
bar
</div>
发布于 2019-09-02 02:14:10
问题在于您正在设置所有div
元素的HTML。相反,您需要循环遍历它们,每一个单独更新一次。为此,您可以向html()
提供一个函数,该函数将根据原始值返回新值。试试这个:
$("div").html(function(i, html) {
return html.replace(/\(.*\)/g, '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>foo (remove this)</div>
<div>bar</div>
发布于 2019-09-02 02:18:45
jQuery不知道哪个div是用来替换内容的。您可以使用每个()
$( "div" ).each(function( index ) {
$( this ).html($( this ).html().replace(/\(.*\)/g, ''))
});
https://stackoverflow.com/questions/57755113
复制相似问题