简体   繁体   English

页面刷新后,如何通过多个单选按钮从JS的localStorage中检索数据?

[英]How to retrieve data from localStorage in JS from multiple radio buttons after page refresh?

This is my first question so.. be gentle and I'm sorry if there is some mistake. 这是我的第一个问题,请保持温和,如果有任何错误,我深表歉意。 Thank you. 谢谢。

I have groups of radio buttons and this is the HTML: 我有几组单选按钮,这是HTML:

<div class="radio">
   <label for="a_a">
       <input type="radio" name="some_name" id="a_a" value="some_value">
   </label>
   <label for="a_b">
       <input type="radio" name="some_name" id="a_b" value="some_value">
   </label>
</div>
<div class="radio">
   <label for="b_b">
       <input type="radio" name="some_name" id="b_b" value="some_value">
   </label>
   <label for="b_c">
       <input type="radio" name="some_name" id="b_c" value="some_value">
   </label>
</div>

and this is the JS: 这是JS:

$(".radio label").on('click', function (e) {
     var input_id = $(this).children().attr('id');
     var input_value = $(this).children().attr('value');
     localStorage.setItem(input_value, input_id);
});
var itemID = localStorage.getItem("option");
    if (itemID !== null) {
        $("input[id=\"" + itemID + "\"]").click();
};

This works well, but the problem is that I'm getting the id only of the last clicked radio button and the question is: How to get the id's from both groups of radio buttons. 这很好用,但问题是我仅获得最后单击的单选按钮的ID,而问题是:如何从两组单选按钮获取ID。 Please, be aware that there might be more than 2 groups of radio buttons. 请注意,可能有两组以上的单选按钮。

Thank you. 谢谢。

Are you looking for something like this? 您是否正在寻找这样的东西? https://jsfiddle.net/sxh0n7d1/15/ https://jsfiddle.net/sxh0n7d1/15/

what do you want to do with the values? 您想用这些值做什么?

window.onbeforeunload = function() {
     $('input[type="radio"]').each(function(){    
        var id = $(this).attr('id');
        var value = $(this).val();
       localStorage.setItem(id, value);
    }); 
}
window.onload = function() { 
    $('input[type="radio"]').each(function(){    
       var id = $(this).attr('id');
       var getValue = localStorage.getItem(id);
       alert("value = "+getValue+" id = "+id);
    }); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM