gpt4 book ai didi

javascript - Show more/Show less 在刷新时停留在页面上

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:06 28 4
gpt4 key购买 nike

因此,在实现上一个问题的 jQuery 代码后,我注意到以下内容,每当人们添加位于显示较少/显示更多菜单中的产品时,系统会刷新页面,因为它会重新计算价格,因此也会刷新页面。但是当发生这种情况时,菜单会关闭,然后他们需要再次单击“显示更多”按钮。如何解决?

//this will execute on page load(to be more specific when document ready event occurs)
if ($('.ty-compact-list').length > 3) {
$('.ty-compact-list:gt(2)').hide();
$('.show-more').show();
}

$('.show-more').on('click', function() {
//toggle elements with class .ty-compact-list that their index is bigger than 2
$('.ty-compact-list:gt(2)').toggle();
//change text of show more element just for demonstration purposes to this demo
$(this).text() === 'Show more' ? $(this).text('Show less') : $(this).text('Show more');
});
.ty-compact-list {
padding: 5px 5px 5px 0px;
float: left;
width: 100%;
}
.show-more {
display: none;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="ty-compact-list">Product 1</div>
<div class="ty-compact-list">Product 2</div>
<div class="ty-compact-list">Product 3</div>
<div class="ty-compact-list">Product 4</div>
<div class="ty-compact-list">Product 5</div>
<div class="ty-compact-list">Product 6</div>
<div class="show-more">Show more</div>
</div>

提前致谢!

最佳答案

正如 Mohit 所说,您可以使用 localStorage,您的代码将如下所示:

var isCompactListOpen = localStorage.getItem('isCompactListOpen') || false;

function setButtonText() {
if (isCompactListOpen) {
$(this).text('Show less');
} else {
$(this).text('Show more');
}
}

if ($('.ty-compact-list').length > 3) {
setButtonText();
$('.show-more').show();
if (!isCompactListOpen) {
$('.ty-compact-list:gt(2)').hide();
}
}

$('.show-more').on('click', function() {
//toggle elements with class .ty-compact-list that their index is bigger than 2
$('.ty-compact-list:gt(2)').toggle();
//change text of show more element just for demonstration purposes to this demo
isCompactListOpen = !isCompactListOpen;
localStorage.setItem('isCompactListOpen', isCompactListOpen);
setButtonText();
});

关于javascript - Show more/Show less 在刷新时停留在页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39180122/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com