2012-10-23 38 views
2

我試圖在重新加載後保留複選框狀態時複選框選中或未選中,並且if語句用於選中並取消選中。我做錯了什麼或者做什麼是最好的方式?重新加載後保留複選框頁

$('.js-bbCheckbox').click(function(event) { 

    $('.js-bbCheckbox').change(function(){ 
      if($(this).is(':checked')){ 
       window.location = '?filter=topRated'; 

      }else{ 
       window.location = '?filter=nottopRated'; 
      } 
     }); 
+0

我不是網絡編程方面的專家,但我認爲在頁面重新加載後,您需要使用cookie來保存數據。但我想知道別人怎麼說。 –

+0

試着看看[https://github.com/hck/jquery.cookie](https://github.com/hck/jquery.cookie) – SpYk3HH

回答

0

所以,你能設置位置,但你需要的頁面改變基於過濾器的複選框。這樣,你不需要保存一個cookie。

$(document).ready(function() { 
     var topRated = new RegExp("[?|&]filter=topRated"); 
     $('.js-bbCheckbox').prop('checked', function() { 
      var filter = window.location.search.match(topRated); 
      return filter != null; 
     }).change(function() { 
      window.location = $(this).is(':checked') ? '?filter=topRated' : window.location.toString().replace(topRated, ""); 
     }); 
    }); 
+0

非常感謝,而不是?filter = nottopRated我可以擺脫?filter = topRated in else condition?基本上我不想在我的網址中的任何其他條件的參數。 –

+0

@ ShoaibUd-Din我編輯它不使用「?filter = nottopRated」 – raykendo

+0

嗯可能是我問錯了,這是我想要做的:當我取消選中然後?filter = topRated應該從url中移除 –

0

這並不完全錯誤,因爲它會起作用。 但是,一旦用戶關閉該頁面並再次打開該頁面,該複選框將具有其默認狀態。

如果您想保留會話之間的複選框狀態,您可以使用cookie。 您可以使用document.cookie屬性通過JavaScript設置Cookie,但您最好查看它,因爲它很複雜。

但是,如果您在此應用程序上使用任何服務器端技術,則可以從此處設置Cookie。例如,在PHP中,它會這樣:

$_COOKIE['checkbox-topRated'] = isset($_GET['topRated']); 

然後,當您打印複選框時,您檢查該cookie是否爲真。 這將是這樣的:

$checked = ''; 
if ($_COOKIE['checkbox-topRated']) { 
    $checked = ' checked="checked"'; 
} 

echo '<type input="checkbox" name="topRated"'.$checked.'>'; 
相關問題