触发点击无线电切换cookie不起作用

时间:2014-03-31 13:27:20

标签: javascript jquery html cookies click

根据this Stack Overflow q/a中的建议,我试图通过cookie触发点击。 cookie是在单选按钮选择上设置的。切换的两个div中的一个需要设置为隐藏。

问题:初始if语句未触发点击。

if($.cookie('light-or-dark')) {
    $($.cookie('light-or-dark') + '-radio').attr('checked', true).trigger('click');
    } else {
    $('#theme-schemes-dark').hide();
  };

// the toggle on radio button change function
$('[name=light-dark-radio]').change(function(){
    $('#theme-schemes-light').toggle('medium');
    $('#theme-schemes-dark').toggle('medium');

    // set cookie on toggle state
    $.cookie('light-or-dark', '#theme-schemes-' + this.value, {expires:365, path: '/'})
  })

HTML:

<div class="selection-wrap">
  <label>
    <input type="radio" name="light-dark-radio" id="theme-schemes-light-radio" value="light" checked>
    Light
  </label>
  <label>
    <input type="radio" name="light-dark-radio" id="theme-schemes-dark-radio" value="dark">
    Dark
  </label>
</div>

<!-- first div -->
<div class="selection-wrap" id="theme-schemes-light">
  <a class="theme-scheme-btn color-box bg-blue" id="defaultThemeScheme" href="#">Light 1</a>
  <a class="theme-scheme-btn color-box bg-yellow" href="#">Light 2</a>
</div>

<!-- second div - hidden by default -->          
<div class="selection-wrap" id="theme-schemes-dark" style="display: none">
  <a class="theme-scheme-btn color-box dark-color-blue" href="#">Dark 1</a>
  <a class="theme-scheme-btn color-box dark-color-yellow" href="#" >Dark 2</a>
</div>

A FIDDLE to better illustrate

非常需要洞察力。

2 个答案:

答案 0 :(得分:0)

我似乎没有同样的问题。 (http://jsfiddle.net/jaLQZ/3/

  $($.cookie('light-or-dark') + '-radio').click(function(){
    alert( 'click' + this.value );
  });

  if($.cookie('light-or-dark')) {
    $($.cookie('light-or-dark') + '-radio').attr('checked', true).trigger('click');
    } else {
    $('#theme-schemes-dark').hide();
  };

  $('[name=light-dark-radio]').change(function(){
    $('#theme-schemes-light').toggle('medium');
    $('#theme-schemes-dark').toggle('medium');
    // set cookie on toggle state
    $.cookie('light-or-dark', '#theme-schemes-' + this.value, {expires:365, path: '/'});
  })

也许您使用的浏览器不支持cookie插件?

答案 1 :(得分:0)

试试这个,我改变了恢复div的代码

  if($.cookie('light-or-dark')) {

$($.cookie('light-or-dark') + '-radio').attr('checked', true);
   $('#theme-schemes-light').hide();
   $('#theme-schemes-dark').hide();
   $($.cookie('light-or-dark')).show();
} else {
$('#theme-schemes-dark').hide();
};

$('[name=light-dark-radio]').change(function(){
$('#theme-schemes-light').toggle('medium');
$('#theme-schemes-dark').toggle('medium');
// set cookie on toggle state
$.cookie('light-or-dark', '#theme-schemes-' + this.value, {expires:365, path: '/'});
})