jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了当目标类的多个实例位于同一页面上时,如何使用jQuery计算单个块中的子节点数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在页面上有几个块,列出了相关博客文章内容内容.相关文章.

这些块被编码以返回所有结果.但是为了防止列表过长,我认列表只显示3个项目,并且在“显示更多”按钮中工作,点击时触发手风琴效果显示剩余项目(如果有).

我遇到的问题是显示更多按钮正在显示,即使块没有超过3项.似乎size()计算两个块的总子节点,而不是单独的每个块.

当然,我可以针对2个独特的选择器并使其正常工作.但是我希望这个脚本可以重复使用,而不必每次我需要另一个手风琴块时总是添加一个新的选择器.

我现在拥有它的方式,无论何时你想要将一个手风琴效果应用于一个块,你只需要在包含HTML列表的任何块上向外包装器添加一个“accordion”类.

这是我的代码.

(function($) {
    $(document).ready(function() { 
        /**
         * Define variables
         */
        var parentSELEctor = $('.block-views .accordion ul'),controlsHTML = $('<div class="show-more"><button>Show More</button></div>'),count = $(parentSELEctor).children().size();

        /**
         * Wrap all items we want to show/hide except for the first 3
         */
        $(parentSELEctor).children().not(':nth-child(1),:nth-child(2),:nth-child(3)').wrapAll('<div class="slide-content" />');

        /**
         * Hide content that should be hidden by default
         */
        $('.slide-content').hide();

    /**
     * Insert open/close button if there are more than three items in list
     */
    if (count > 3) {
    $(controlsHTML).insertAfter(parentSELEctor);
    }

        /**
         * Build the expanding content container and attach it to a click event
         */
        $(".show-more button").toggle(
            function () {
                $(this).toggleClass('collapse');
                $(this).text("Show Less");
                $(this).parents('.item-list').find('.slide-content').slideDown();
            },function () {
                $(this).toggleClass('collapse');
                $(this).text("Show More");
                $(this).parents('.item-list').find('.slide-content').slideUp();
            }
        );
    });
}(jQuery));

解决方法

您需要通过手风琴进行迭代并检查每个手风琴的长度:

(function($) {
    $(function() { 

        $('.block-views .accordion ul').each(function(i,elm) {
            var ctrl = $('<div class="show-more"><button>Show More</button></div>'),count = $(this).children().length;
            if (count > 3) {
                $(this).after(ctrl);
            }
        });

        $(".show-more button").data('state',truE).on('click',function () {
            var state = $(this).data('state');

            $(this).toggleClass('collapse').text("Show "+(state?'Less':'More'));
                   .parents('.item-list').find('.slide-content').slideToggle().data('state' !statE);
        });
    });
}(jQuery));

另请注意,使用这种方式的切换也已弃用!

大佬总结

以上是大佬教程为你收集整理的当目标类的多个实例位于同一页面上时,如何使用jQuery计算单个块中的子节点数全部内容,希望文章能够帮你解决当目标类的多个实例位于同一页面上时,如何使用jQuery计算单个块中的子节点数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。