我有一个div <div id="masterdiv">,它有几个子<div>s。

例子:

<div id="masterdiv">
  <div id="childdiv1" />
  <div id="childdiv2" />
  <div id="childdiv3" />
</div>

如何使用jQuery清除所有子<div>的内容里面的主<div> ?


当前回答

jQuery的empty()函数就是这样做的:

$('#masterdiv').empty();

清除主div。

$('#masterdiv div').empty();

清除所有子div,但保留主div完整。

其他回答

jQuery建议你使用".empty()",".remove()",".detach()"

如果你需要删除元素中的所有元素,使用下面的代码:

$('#target_id').empty();

如果你需要删除所有元素,使用以下代码:

$('#target_id').remove();

i和jQuery小组不建议使用SET函数像.html() .attr() .text(),这是什么?如果你想设置任何你需要的东西

裁判:https://learn.jquery.com/using-jquery-core/manipulating-elements/

$("#masterdiv > *").text("")

or

$("#masterdiv").children().text("")

当你使用任何服务或数据库通过id将数据追加到div中时,首先尝试它是空的,就像这样:

var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div").text("");

可以使用.empty()函数清除所有子元素

 $(document).ready(function () {
  $("#button").click(function () {
   //only the content inside of the element will be deleted
   $("#masterdiv").empty();
  });
 });

要查看jquery .empty(), .hide(), .remove()和.detach()之间的比较,请访问http://www.voidtricks.com/jquery-empty-hide-remove-detach/