我有一个 div,我想删除该 div 内部的所有 HTML。
我如何做到这一点?
我如何做到这一点?
我不认为empty()
或html()
是你要找的。我猜你正在寻找类似于PHP中的strip_tags
的东西。如果你想做到这一点,那么你需要添加这个函数:
jQuery.fn.stripTags = function() {
return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
};
假设这是你的HTML:
<div id='foo'>This is <b>bold</b> and this is <i>italic</i>.</div>
然后你执行:
$("#foo").stripTags();
这将导致:
<div id='foo'>This is bold and this is italic.</div>
另一种方法是将HTML设置为空字符串:
$('#mydiv').html('');
function stripsTags(text)
{
return $.trim($('<div>').html(text).text());
}
<script type="text/javascript">alert('sasa');</script>
,它会弹出警报,因此不安全。 - umpirsky<div class="prtDiv">
<div class="first">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
</div>
$('.first').empty();
结果将会是这样的
<div class="prtDiv">
<div class="first">
</div>
</div>
如果您想再次添加它们,我们可以尝试使用detach()进行临时分离。
$('.first').detach();
var htmlJ = $('<p><span>Test123</span><br /><a href="http://www.google.com">goto Google</a></p>');
console.log(htmlJ.text()); // "Test123goto Google"
<script type="text/javascript">alert('sasa');</script>
,它会弹出警报,因此不安全。 - umpirsky