我正在尝试创建一个按钮显示“查看所有照片”的图库,通过单击该框隐藏的照片正在展开,按钮文本将更改为“隐藏所有照片”。
然后在单击“隐藏所有照片”后,展开的图像正在折叠,按钮文本将更改为“查看所有照片”。其实我想做到这一点。
但问题是它只能运作一次。当我第二次点击“查看所有照片”时,隐藏区域没有扩展,按钮文本也没有改变。
$(document).ready(function() {
//Gallery Show all photos
$('.trigger-details > button').click(function(){
$('.single-gallery-image.hidden-lg').removeClass('hidden-lg').addClass('gallery-expanded');
$(this).addClass('hide-button').text('Hide All Photos');
$('.hide-button').click(function(){
$('.gallery-expanded').removeClass('gallery-expanded').addClass('hidden-lg');
$(this).removeClass('hide-button').text('View All Photos');
});
});
});
答案 0 :(得分:2)
$('.hide-button').click()
是用于将事件委托给DOM元素的。
然后,在那句话中你做$(this).removeClass('hide-button')
。
因此它失去了它的类,并且因为第一个事件只被委托/调用一次,所以你不能再次附加它。你最好只有一个事件(不像你在这里那样嵌套)控制两个状态。
$('.trigger-details > button').click(function(){
if ($(this).hasClass('hide-button')) {
// do your showing logic
} else {
// do your hiding logic
}
});
答案 1 :(得分:1)
尝试在文档级别设置点击事件,而不是嵌套在第一次点击
中$(document).on('click','.trigger-details > button', function(){
$('.single-gallery-image.hidden-lg').removeClass('hidden-lg').addClass('gallery-expanded');
$(this).addClass('hide-button').text('Hide All Photos');
});
$(document).on('click','.hide-button', function(){
$('.gallery-expanded').removeClass('gallery-expanded').addClass('hidden-lg');
$(this).removeClass('hide-button').text('View All Photos');
});