【问题标题】:Trigger click on radio button with remembering selection on page refresh触发单击单选按钮并记住页面刷新时的选择
【发布时间】:2015-05-17 02:48:54
【问题描述】:

此题不重复。

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

我能够分别实现以下目标:

  1. 在页面加载时触发点击“radio1”。因此,无论何时加载页面,都会单击该按钮。
  2. 记住用户手动单击的选定单选按钮,使用 Joseph Silber 在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>

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

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

【问题讨论】:

    标签: javascript php jquery html radio-button


    【解决方案1】:

    为什么不直接设置默认单选: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 就绪时触发默认收音机的事件处理程序(就像您在代码中使用 .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 />
    ...
    

    这样您就可以在本地拥有它 checked,而不是以编程方式。然后覆盖其prop 取决于localStorage 中的内容


    EDIT(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

    【讨论】:

    • 感谢您的回答!我需要单击它,因为除非单击单选按钮并且不仅选中,否则不会显示嵌套项目。我看到您评论了“如果存在本地存储,则覆盖收音机”,这就是我要找的!但如果本地存储存在,我需要覆盖并单击。因此,如果“radio2”存在于本地存储中,它会触发点击它。我试图将这部分.trigger("click"); 附加到本地存储的代码中,但是没有用。我希望你能在这部分帮助我。非常感谢。
    • @JFallz,看看我回答的 EDIT 部分。这是您需要实现的目标吗?
    • 是的,是的!太感谢了!你真棒。我现在将其标记为已接受的答案。一次又一次地感谢您的光临! :) @Artur Filipiak
    • @JFallz,很高兴我能帮上忙! :)
    猜你喜欢
    • 2012-06-24
    • 1970-01-01
    • 2020-12-16
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2014-04-10
    相关资源
    最近更新 更多