用jQuery清空元素的最有效方法是什么 [英] What's the most efficient way to empty an element with jQuery

查看:116
本文介绍了用jQuery清空元素的最有效方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有这些都可以做到,但是最有效的方法是什么?

All these do it, but what is the most efficient way?

$(selector).html('');
$(selector).text('');
$(selector).children().remove();

推荐答案

请参见 http://api.jquery.com /空

$(selector).empty();

这绝对是最清晰的方法,几乎​​绝对是最有效的方法.

This is definitely the most clear way, and almost definitely the most efficient.

由于它是jQuery内部的,因此它可能比.children().remove()更有效,并且肯定没有降低的效率.

Since it's jQuery-internal it's probably more efficient than .children().remove(), and certainly no less efficient.

我不得不认为.html('').text('')的效率都较低,因为它们调用html解析器,而不仅仅是像其他方法一样处理dom节点.即使它们碰巧效率更高,效率的任何提高也很容易被使用empty()的清晰性所抵消,除非您确实出于特定原因需要对该部分进行优化(在这种情况下,我将仅对所有部分进行基准测试)选项).

I'd have to think that .html('') and .text('') are both less efficient since they invoke html parsers rather than just dealing with dom nodes like the other methods. And even if they happened to be more efficient, any gains in efficiency would easily be outweighted by gains in clarity of using empty(), unless you really need to optimize that section for a specific reason (in which case I'd just benchmark all the options).

这篇关于用jQuery清空元素的最有效方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆