javascript - 触发单击单选按钮并记住页面刷新时的选择

标签 javascript php jquery html radio-button

此题不重复。

我有两个单选按钮(radio1、radio2)。

我能够单独实现以下目标:

  1. 在页面加载时触发对“radio1”的点击。因此,无论何时加载页面,都会点击该按钮。
  2. 使用 this answer 中描述的本地存储记住用户手动点击的选定单选按钮约瑟夫西尔伯。因此,如果用户手动点击“radio2”然后刷新页面,它会记住该选择。

问题是我不能同时使用这两种方法。因为触发的点击总是占用本地存储,这使得页面刷新时选择的单选按钮不被记住。

默认情况下,我需要在页面加载时单击(未选中)“radio1”,但是当用户手动单击“radio2”时,它会记住该选择,并且每当刷新页面时,都会单击“radio2”尊重用户的选择。

我尝试了很多代码来组合我必须让它们一起工作的代码,但我无法弄清楚。

在页面加载时触发点击单选按钮的代码:

<script type="text/javascript">
$(document).ready(function() {
  $("#radio1 input:radio").click(function() {
    alert("clicked");
   });
  $("input:radio:first").prop("checked", true).trigger("click");
});
</script>

本地存储的代码;记住电台选择:

<script type="text/javascript">
$(function()
{
    $('input[type=radio]').each(function()
    {
        var state = JSON.parse( localStorage.getItem('radio_'  + this.id) );

        if (state) this.checked = state.checked;
    });
});

$(window).bind('unload', function()
{
    $('input[type=radio]').each(function()
    {
        localStorage.setItem(
            'radio_' + this.id, JSON.stringify({checked: this.checked})
        );
    });
});
</script>

同样,它们都可以正常工作,但单独使用时,它们中的任何一个都可以工作。

如果有人能帮助我使这两种方法一起工作,我将不胜感激。

最佳答案

为什么不设置默认的单选按钮 :checked 属性而是设置 .trigger('click')

$(function(){
    //state default radio ':checked' property there:
    $("input:radio:first").prop("checked", true);

    $("#radio1 input:radio").click(function() {
        alert("clicked");
    });

    // overwrite radio ':checked' property there (if exists in localStorage) :
    $('input[type=radio]').each(function(){
        var state = JSON.parse( localStorage.getItem('radio_'  + this.id) );

        if (state) this.checked = state.checked;
    });
});

$(window).bind('unload', function(){
    $('input[type=radio]').each(function(){
        localStorage.setItem(
            'radio_' + this.id, JSON.stringify({checked: this.checked})
        );
    });
});

JSFiddle


或者,如果您需要在 DOM 准备就绪时触发默认 radio 的事件处理程序(就像您在代码中使用 .trigger('click') 所做的那样),请使用:

$(function(){
    //state default radio ':checked' property there and run its `click` event handler:
    radioClick.call($("input:radio:first").prop("checked", true));

    $("#radio1 input:radio").click(radioClick);

    // method triggered on radio click, will skip the localStorage modification:
    function radioClick() {
        // you can refer here to 'this' as to clicked radio
        alert($(this).val());
    }

    // overwrite radio ':checked' property there (if exists in localStorage) :
    $('input[type=radio]').each(function(){
        var state = JSON.parse( localStorage.getItem('radio_'  + this.id) );

        if (state) this.checked = state.checked;
    });
});

$(window).bind('unload', function(){
    $('input[type=radio]').each(function(){
        localStorage.setItem(
            'radio_' + this.id, JSON.stringify({checked: this.checked})
        );
    });
});

JSFiddle


或者,甚至更好,在 HTML 中设置默认的单选按钮 checked 属性:

<input type=radio id=radio1 value=radio1 name=radio checked />
<input type=radio id=radio2 value=radio2 name=radio />
<input type=radio id=radio3 value=radio3 name=radio />
...

这样您就可以在本地检查,而不是以编程方式。然后根据 localStorage

中的内容覆盖其 prop

编辑(OP 对答案的评论)

$(function () {

    $('input[type="radio"]').click(function () {
        localStorage.setItem('radioIdSelected', $(this).attr('id'));
        // your method to run on selected radio button (alert for demo):
        alert($(this).attr('id'));
    });

    var storageRadio = localStorage.getItem('radioIdSelected');

    if (storageRadio !== null && storageRadio !== undefined && $('#' + storageRadio).length) {
        $('#' + storageRadio).trigger('click');
    } else {
        $('input[type="radio"]:first').trigger('click');
    }

});

JSFiddle

关于javascript - 触发单击单选按钮并记住页面刷新时的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29052260/

相关文章:

php - CodeIgniter 和多语言数据库

jquery - Html.ActionLink : div as target

javascript - jQuery - $(this) + 选择器 - .each()

php - 如何通过ajax访问json_decode()数据

javascript - AngularJS - 从服务访问 Controller 内的元素

php - SendMail 的替代方案

javascript - 显示元素内的多个字符

javascript - Jquery 对我的元素没有影响

javascript - 显示/隐藏带有链接的多个 Div

javascript - 什么时候开始删除视频元素以防止浏览器延迟?