5

我有一些工作正常的代码,但它变得太慢了:

HTML:

我有一个包含大约 50 个ul元素的容器。每个ul元素都有一个h4标题,后跟一系列li元素。如果没有可见的线元素,该函数将隐藏标题。

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();
                    }
                }); 
            }

在我改变li元素的性质之前,它的工作非常可接受。每个li现在都是一个迷你桌子,包括<table><tr><td>icon</td><td>text</td></tr></table>. 现在需要 2 秒来处理,而之前它只需要不到半秒的时间。(该表用于停止图标下的文本换行。)

我承认我不太明白为什么在每个元素中添加额外的元素li会大大减慢 DOM 处理,因为我使用.children选择器只深入一层 DOM。

我也试过:

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

$('#container').children().children('h4')为良好的措施。

同样值得注意的是,当li可见元素很多时,它比可见元素少时慢得多。然而,现在没有更多的行了,而不是它工作得很快(即,在表格被放入每一行之前)。

任何建议都非常感谢,但请不要要求我发布比我更多的代码:)

谢谢。

4

2 回答 2

2

尝试:

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

但我同意 RobG,您的标记可能不正确。

于 2012-07-10T05:33:50.543 回答
2

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.

于 2012-07-10T05:37:41.417 回答