当另一个项目被隐藏时,jquery 仅工作第一个项目

问题描述 投票:0回答:1

我写了一个jquery来显示更多和显示更少的项目。它仅适用于第一项。但是当我要去另一个项目并选择显示更多项目时。它不起作用。据我了解,当我切换另一个项目时,jquery 加载并显示:隐藏上一节并显示:阻止当前部分。这就是为什么我的 jquery 不能用于隐藏部分。谁能帮我解决这个问题吗? 谢谢。

这是我的代码。

 var item_length = $('.button_img_custom_class .buttonSelectionItemContainer .ButtonSelectorItem').length;
    var target = $('.button_img_custom_class .buttonSelectionItemContainer');
    $(target).each(function () {
        $(this).toggleClass("example");
        var items = $(this).children().length;
    
        if (items > 6) {
            $(this).css({'max-height': '115px', 'overflow': 'hidden'});
            $(this).after('<a id="show-more">Show More</a>');
        }
        ;
    })
    $('#show-more').click(function () {
        if ($(this).prev().hasClass('open')) {
            $(this).prev().removeClass('open');
            $('#show-more').html('Show More');
            $(this).prev().css({'max-height': '115px'});
        } else {
            $(this).prev().addClass('open');
            $('#show-more').html('Show Less');
            $(this).prev().css({'max-height': '1000px'});
        }
    })
jquery hide show
1个回答
0
投票

你正在循环执行此操作:

$(this).after('<a id="show-more">Show More</a>');

这意味着您正在创建具有相同 id

多个
元素,这是无效的。

仅适用于第一项。

因为一旦 jQuery、JavaScript、浏览器等找到具有该

#show-more
的元素,就没有理由去寻找另一个
id
元素。不应该再有一个了。

不要使用

id
,而使用
class

$(this).after('<a class="show-more">Show More</a>');

并将点击处理程序绑定到该类:

$('.show-more').click(function () {
    if ($(this).prev().hasClass('open')) {
        $(this).prev().removeClass('open');
        $(this).html('Show More');
        $(this).prev().css({'max-height': '115px'});
    } else {
        $(this).prev().addClass('open');
        $(this).html('Show Less');
        $(this).prev().css({'max-height': '1000px'});
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.