使用Sessionstorage中的值检查和取消选中Jquery中的复选框

时间:2015-07-24 09:54:13

标签: jquery html dom

我正面临一个问题,我试图设置一些复选框,依赖于我在sessionstorage中的值。我有一个主窗体,其中我有一个表格,每个单元格中都有一个复选框。现在单击一个图标,我在浏览器的另一个选项卡中显示相同的表,更多详细信息,我需要选中相同的复选框。两个窗口中的复选框都是相同的。所以我使用SessionStorage将选择值从一个选项卡共享到另一个选项卡。这是代码段。

  jQuery(document).ready(function() { 
  // this is to store all the existing checks into SessionStorage 
  jQuery('input[id^="chx_box_"]').each(function() {
      var chk_box = jQuery(this).attr("id");
      var IsChecked = (jQuery(this).attr('checked'))?true:false;
      sessionStorage.setItem(chk_box, IsChecked );
  });

});

在新标签中,我有这段代码。

  // this is update all the checkboxes with the current selection
  $('input[id^="chx_box_"]').each(function() {

      // Clearing the previous selections
      $(this).prop( 'checked', false  );

      var chk_box = $(this).attr("id");
      console.log( chk_box  );     // I am getting the checkbox id here
      var IsChecked = sessionStorage.getItem(chk_box);
      console.log( IsChecked  );   // I am getting true or false here

      // setting the current selection from the parent window

      // This is checking all the checkboxes in the new tab table....
      $(this).prop('checked', IsChecked  ); 


      // tried these below two as per some of the solutions from 
      // various questions in Stack Over flow. But no 
      // $(this).attr('checked', IsChecked  );
      // $(this)[0].checked =  IsChecked;

  });

我正在使用 jquery-1.11.3.min.js 。 我有两个问题。 1.如果用户在一个窗口中选中一个复选框并移动到另一个窗口并验证其选择,如何更新复选框值

  1. 为什么上面的代码会检查所有复选框,即使我发送的是true或false参数。
  2. 感谢您的支持。

2 个答案:

答案 0 :(得分:2)

我认为这是因为你回到了Strings" true"或"假"从

回来
var IsChecked = sessionStorage.getItem(chk_box);

在JavaScript中,每个非空字符串都是真实的。这也适用于String" false"。

你可以尝试

var IsChecked = JSON.parse(sessionStorage.getItem(chk_box));

答案 1 :(得分:1)

对于您的问题1,您可以使用storage事件。在localStorage中存储值时,此事件仅在同一域中的其他选项卡/窗口上触发。

为此您必须使用localStorage,不能使用sessionStorage,因为sessionStorage只对一个选项卡是本地的。数据不会从一个标签传递到另一个标签。

因此,当用户单击复选框时,您需要更新localStorage中的值,并且将触发存储事件。

$( window ).on( 'storage', function( ) {
    // your code here to handle the values.
} );

不幸的是,即使localStorage和sessionStorage在IE中工作,这个事件在IE中也没有按预期工作(caniuse,见"已知问题")

对于你的问题2,这是因为localStorage只存储字符串。您必须先将其转换为布尔值。

相关问题