触发单击单选按钮,并在页面刷新时记住选择

此问题不重复。</ p>

我有两个单选按钮(radio1 ,radio2)。</ p>

我能够实现以下功能,但是分开:</ p>


  1. 触发点击“radio1” 页面加载。 因此,无论何时加载页面,都会单击该按钮。</ li>
  2. 记住用户手动点击的所选单选按钮,使用这个答案由Joseph Silber撰写。 因此,如果用户手动点击“radio2”然后刷新页面,它会记住该选择。</ li>
    </ ol>

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

    我需要在页面加载时单击(未选中)“radio1” 默认情况下,但当用户手动点击“radio2”时,它会记住该选择,每当刷新页面时,将根据用户的选择点击“radio2”。</ p>

    I 我尝试了很多代码组合,让它们一起工作,但我无法理解它。</ p>

    触发单击单选按钮的代码 页面加载:</ strong> </ p>

     &lt; script type =“text / javascript”&gt; 
    $(document).ready(function(){
    $ (“#radio1 input:radio”)。click(function(){
    alert(“clicked”);
    });
    $(“input:radio:first”)。prop(“checked”,true ).trigger(“click”);
    });
    &lt; / script&gt;
    </ code> </ pre>

    本地存储的代码; 记住无线电选择:</ strong> </ p>

     &lt; script type =“text / javascript”&gt; 
    $(function()
    {
    $('输入 [type = radio]')。each(function()
    {

    var state = JSON.parse(localStorage.getItem('radio_'+ this.id));

    if 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})
    );
    });
    });

    &lt; / script&gt;
    </ code> </ pre>

    同样,它们都可以正常工作但分开工作,其中一个工作正常。</ p>

    如果有人可以帮助我让两种方法一起工作,我将非常感激。</ p>
    </ div>

展开原文

原文

This question is not duplicated.

I have two radio buttons (radio1, radio2).

I was able to achieve the following, BUT separately:

  1. Trigger a click on "radio1" on page load. So whenever the page is loaded, the button is clicked.
  2. Remember the selected radio button that is manually clicked by user, using local storage described in this answer by Joseph Silber. So if the user manually clicked on "radio2" and then refreshed the page, it remembers that selection.

The problem is that I cannot use both methods at the same time. Because the triggered click always takes over the local storage, which makes the selected radio button not remembered when page is refreshed.

I need "radio1" to be clicked (not checked) on page load by default, but when the user manually clicks on "radio2" it remembers that selection, and whenever the page is refreshed the "radio2" will be clicked with respect to the user's selection.

I tried a lot to make a combination of codes I have to get them both works together, but I couldn't figure it out.

The code for trigger a click on radio button on page load:

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

The code for local storage; remembering radio selection:

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

Again, they both works fine but separately, either one of them will work.

If anyone can help me to make both methods work together, I will really appreciate it.

1个回答

Why not just set the default radio :checked property but .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


Or, if you need to trigger an event handler for default radio (as you do in your code using .trigger('click')) on DOM ready, use this:

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


Alternatively, and even better, set the default radio checked property right in the HTML:

<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 />
...

So that you have it checked natively, not programatically. Then overwrite its prop depends on what is in the localStorage


EDIT (OP comment to the answer)

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

duanba2001
duanba2001 很高兴我能帮助你! :)
5 年多之前 回复
duannian4784
duannian4784 对对对!! 非常感谢! 你真棒。 我现在要把它标记为已接受的答案。 谢谢你一次又一次的时间! :) @Artur Filipiak
5 年多之前 回复
doufei2194
doufei2194 看看我的答案的EDIT部分。 这是你需要实现的吗?
5 年多之前 回复
doukanzhuo4297
doukanzhuo4297 谢谢您的回答! 我需要点击它,因为除非单击单选按钮并且不仅检查了嵌套项,否则不会显示嵌套项。 我看到你评论“覆盖无线电,如果本地存储存在”,这就是我正在寻找的! 但是如果存在本地存储,我需要覆盖并单击。 因此,如果本地存储中存在“radio2”,则会触发对其的单击。 我试图附加这部分.trigger(“点击”); 到本地存储的代码,但它不起作用。 我希望你能帮我解决这个问题。 非常感谢。
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐