简体   繁体   English

$('#foo')可能存在jQuery内存问题.remove()?

[英]Possible jQuery memory issues with $('#foo').remove()?

I've just discovered that when the remove() function is used, the matched elements are not removed from the jQuery object, just the DOM. 我刚刚发现,当使用remove()函数时,匹配的元素不会从jQuery对象中删除,只会删除DOM。

According to the remove() documentation : 根据remove()文档

Removes all matched elements from the DOM. 从DOM中删除所有匹配的元素。 This does NOT remove them from the jQuery object, allowing you to use the matched elements further. 这不会从jQuery对象中删除它们,允许您进一步使用匹配的元素。

Surely if a web app keeps on adding and removing elements from the dom, this will keep using up more and more memory? 当然,如果一个Web应用程序继续添加和删除dom中的元素,这将继续消耗越来越多的内存? Can someone confirm if this is the case? 有人可以确认是否是这种情况? What can be done to avoid this? 可以做些什么来避免这种情况?

I think that it would be garbage collected (eventually) once it falls out of scope. 我认为一旦它超出范围,它将被垃圾收集(最终)。 If you're having problems with excessive memory use, though you might try using the delete operator on the returned object. 如果您在使用过多内存时遇到问题,可以尝试在返回的对象上使用delete运算符。

I have tried to find the answer to my own question by doing a little test. 我试着通过做一点测试来找到自己问题的答案。

<script type="text/javascript">
$(document).ready(function() { 
    for ($i=1; $i<10000; $i++) {
        $('table').append("<tr id=\"test_" + $i + "\"><td>test " + $i + "</td></tr>");
        $('#test_'+($i-1)).remove();
    }
});
</script>
<table>
    <tr><td id="test_0">test 0</td></tr>
</table>

I did variations on the remove() by using: 我使用以下方法对remove()做了各种变体:

var test = $('#test_'+($i-1)).remove();

and with the delete operator (thanks to tvanfosson's suggestion): 并使用删除操作符 (感谢tvanfosson的建议):

var test = $('#test_'+($i-1)).remove();
delete test

Having done these tests I would still just use remove(). 完成这些测试后,我仍然只使用remove()。 Its very hard to tell if there was a memory leak since the memory usage of the browser always increased after reloading the page. 由于浏览器的内存使用量在重新加载页面后总是增加,因此很难判断是否存在内存泄漏。 Perhaps someone else is able to provide a more conclusive answer by testing the code differently. 也许其他人能够通过不同的方式测试代码来提供更确定的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM