因此,在实现上一个问题的jQuery代码后,我注意到以下情况,每当人们添加位于show less / show more菜单中的产品时,系统会刷新页面,因为它会重新计算价格,因此也会重新计算页面。但是当这种情况发生时,菜单关闭,然后他们需要再次单击“显示更多”按钮。如何解决这个问题?
//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>
提前致谢!
答案 0 :(得分:1)
正如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();
});