因此,在尝试了解某些工作后,我想出了这个代码(允许一个更多/更少的按钮,只要页面刷新就会保持打开或关闭状态:
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();
});
但现在它在谷歌Chrome网页控制台中给了我这个错误:
jquery.min.js:4 Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
at dt (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:23993)
at Function.buildFragment (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:31426)
at init.domManip (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:28300)
at init.append (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:26162)
at init.$.fn.(anonymous function) [as append] (http://dev.***.com/var/cache/misc/assets/js/tygh/scripts-4e16721e1fc39760420d82fb157574bd1483617255.js:681:688)
at init.<anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:25287)
at Function.access (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:6600)
at init.text (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:4:25224)
at setButtonText (http://dev.****.com/****/:4641:13)
at http://dev.****.com/****/:4646:3
任何帮助将不胜感激!
答案 0 :(得分:2)
我认为问题可能是因为您使用 this 而不是选择器。 setButtonText 函数中的 this 上下文错误。
试试这个:
function setButtonText() {
if (isCompactListOpen) {
$('.show-more').text('Show less');
} else {
$('.show-more').text('Show more');
}
}