jQuery: counting visible elements - efficiency/speed problems

我只是一个虾纸丫 提交于 2019-12-12 11:05:01

问题


I have some code that works fine but it's become too slow:

HTML:

I have a container that contains about 50 ul elements. Each ul element has a h4 heading followed by a series of li elements. The function hides the heading if no line elements are visible.

Javascript/jQuery:

            function show_or_hide_headings() {
                $('#container').children('ul').each(function (i) {
                    var $this = $(this),
                        $h4 = $this.children(':first');
                    if ($this.children('li:visible').length) {
                        $h4.show();
                    } else {
                        $h4.hide();
                    }
                }); 
            }

It was working quite acceptably until I changed the nature of the li elements. Each li is now a mini table comprising <table><tr><td>icon</td><td>text</td></tr></table>. It now takes 2 seconds to process, whereas it previously worked in less than half a second. (The table is there to stop the text wrapping under the icon.)

I confess I can't quite understand why adding the additional elements into each li should slow down the DOM processing so much because I've used the .children selector to only go one DOM layer deep.

I've also tried:

                $('#container').find('h4').each(function (i) {
                    var $this = $(this);
                    if ($this.siblings('li:visible').length) {
                       $this.show();
                    } else {
                       $this.hide();
                    }
                }); 

and $('#container').children().children('h4') for good measure.

What is notable, too, is that when there are many li elements visible, it is much slower than when few are visible. There are no more lines now, however, than when it worked quite quickly (i.e., before the table was put into each line).

Any advice greatly appreciated, but please don't request I post more code than I have :)

Thanks.


回答1:


I suspect that determining if an element is visible or not is quite expensive. Consider instead adding and deleting a class to hide or show elements. Then you can select them directly based on the class, which will mostly be supported by a host getElementsByClassName or querySelectorAll method.




回答2:


try:

$('h4', '#container').css('display', 'none').filter(function() {
    return $(this).siblings('li:visible').length;
}).css('display', 'block');

but I agree with RobG, you'r markup is probably incorrect.



来源:https://stackoverflow.com/questions/11406964/jquery-counting-visible-elements-efficiency-speed-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!