所有这些都可以做到,但是最有效的方法是什么?
All these do it, but what is the most efficient way?
$(selector).html(''); $(selector).text(''); $(selector).children().remove();推荐答案
请参见 api.jquery /空
$(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清空元素的最有效方法是什么
发布评论