5

I have two div elements inside another. At times, from user interactivity, these two items are removed, and two new elements are placed.

Is it proper to remove the existing elements first? Or just overwrite the html? Or does it even matter?

$('#item1').remove();
$('#item2').remove();
$('#itemWindow').append(newItem1);
$('#itemWindow').append(newItem2);

Or simply

$('#itemWindow').html(newItem1);
$('#itemWindow').append(newItem2);

One is less code, but should the item be removed instead? The items do not have any listeners, but if they did does that make a difference?

I'm an ActionScript developer diving into JS and jQuery. In AS, if any listeners exist, it's proper to remove the item first to sever any ties to the object, for proper memory collection. Are these rules the same with JS and jQuery?

Thanks!

4

4 回答 4

3

他们没有区别。所以你可以继续使用第二种方法。当你使用这个

$('#itemWindow').html(newItem1);

$('#item1')并将 $('#item2')被替换。因此,您可以跳过手动删除它们。

正如@glavić 在评论中提到的,如果你在html这里查看 jQuery 源代码中的方法 定义https://github.com/jquery/jquery/blob/master/src/manipulation.js#L213 你会在最后发现它有这些行

 if ( elem ) {
    this.empty().append( value );
 }

在这种情况下elem是真的。所以元素将是emptied,然后新元素将是appended

如果他们有侦听器,那么您必须以某种方式绑定侦听器,以便它可以与动态添加的元素一起使用,例如使用$.on

于 2012-06-01T20:42:41.523 回答
0

如果 item 有任何监听器,那么第一种方法更合适。.remove()删除项目本身和所有绑定事件。如果项目被删除但不是事件,将来可能会发生错误。但如果没有有界事件,可以使用第二种方法 - 因为代码更少。

于 2012-06-01T20:53:30.643 回答
0

$('#item1').remove(); 将删除 id 为 item1 的元素

$('#item1').html(newItem1); 将在 id 为 item1 的元素中设置 html

于 2012-06-01T20:43:15.770 回答
0

如果您想具体说明您实际要删除的内容,比如说您有一个需要删除的元素,而不是另一个,那么我推荐第一种方法。如果您只是要每次都替换所有内容,那么请随意使用,或者,唯一的问题是什么对您来说更具可读性。

于 2012-06-01T20:47:05.413 回答