2016-02-26 96 views
0

我有多個帶有唯一標識的複選框,這些複選框是動態創建的,我需要單擊此複選框以在頁面刷新時進行檢查。我使用了下面的代碼,但是這會在刷新時檢查所有複選框。在刷新頁面後保持動態創建的複選框

$(function(){ 
    var test = localStorage.input === 'true'? true: false; 
    $('input').prop('checked', test || false); 
}); 

$('input').on('change', function() { 
    localStorage.input = $(this).is(':checked'); 
    console.log($(this).is(':checked')); 
}); 

任何幫助,將不勝感激。

+1

它可能更好地會使用Cookie存儲輸入的信息以及它的不敏感。 localStorage對簡單存儲來說有點矯枉過正,因爲只有在您或用戶將其刪除之前,它纔會被刪除。 –

+0

@Jamie Sterling,我很開放,但我是Javascript新手,我不知道該怎麼做 – aasd

+0

我會爲你寫一個關於如何使用javascript cookies創建和管理輸入的答案。我們都去過那裏。 :-) –

回答

0

$(document).ready(function() { 
 
    if (sessionStorage.getItem('checked-checkboxes') && $.parseJSON(sessionStorage.getItem('checked-checkboxes')).length !== 0) 
 
    { 
 
     var arrCheckedCheckboxes = $.parseJSON(sessionStorage.getItem('checked-checkboxes')); 
 
     //Convert checked checkboxes array to comma seprated id 
 
     $(arrCheckedCheckboxes.toString()).prop('checked', true); 
 
    } 
 
    $("input:checkbox").change(function() { 
 
     var arrCheckedCheckboxes = []; 
 
     // Get all checked checkboxes 
 
     $.each($("input:checkbox:checked"), function() { 
 
      arrCheckedCheckboxes.push("#" + $(this).attr('id')); 
 
     }); 
 
     // Convert checked checkboxes array to JSON ans store it in session storage 
 
     sessionStorage.setItem('checked-checkboxes', JSON.stringify(arrCheckedCheckboxes)); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
Checkbox 1: <input type="checkbox" id="chk1"> <br> 
 
Checkbox 2: <input type="checkbox" id="chk2"> <br> 
 
Checkbox 3: <input type="checkbox" id="chk3"> <br> 
 
Checkbox 4: <input type="checkbox" id="chk4"> <br> 
 
Checkbox 5: <input type="checkbox" id="chk5"> <br>

+0

請檢查我的更新答案。它比以前的答案要短。 –