2017-01-05 203 views
2

因此,在嘗試讓某些東西工作後,我想出了這個代碼(它允許更多/更少的按鈕保持打開或關閉狀態每當該頁面將被刷新:jquery.min.js:4 Uncaught TypeError:無法讀取未定義的屬性'createDocumentFragment'

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 Web控制檯:

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 

任何幫助,將不勝感激

回答

2

我認爲這個問題可能是因爲你正在使用這個而不是選擇器。 這個上下文錯誤在setButtonText函數中。

試試這個:

function setButtonText() { 
    if (isCompactListOpen) { 
     $('.show-more').text('Show less'); 
    } else { 
     $('.show-more').text('Show more'); 
    } 
} 
+0

你是我的救命恩人! – SimplySavage

+0

只是還有一個問題,它不會自動顯示更少的項目,它顯示更多,直到你按下顯示更少。這可以設置爲默認的某種方式? – SimplySavage

+0

您需要做的就是在頁面加載時運行setButtonText函數。 –

相關問題