2011-11-29 123 views
1

我一直在挖掘.attr().prop(),但是在获取无线选择选项时遇到了很多麻烦。jQuery - 单选按钮状态变化

基本前提是我有两个单选按钮,其中一个是默认选中的。当选择一个不同的单选按钮时,它应该显示一系列具有所调用的类别的div,其中.show()。我有它的部分工作,但是当你选择相同的单选按钮已经被选中,它会再次运行.show()行动 - 所以我试图添加一个检查,看看'检查'是否定义或不,但它不是啮合。我的大脑处于突破点,所以任何帮助将不胜感激。而且 - 我敢肯定有一个更有效的方式来写这篇文章,所以使用jQuery 1.7.1如果出现...请:)

jQuery(document).ready(function() { 

    if (jQuery('#section-of_homepage_display input[value="slideshow"]:checked').val() === undefined) { 
     jQuery('#section-of_homepage_display input[value="slideshow"]').click(function() { 
      jQuery('.homepage_display').hide(400); 
      jQuery('.homepage_display_slides').show(400); 
     }); 
    } 

    if (jQuery('#section-of_homepage_display input[value="slideshow"]:checked').val() !== undefined) { 
     jQuery('.homepage_display_slides').show(); 
    } 

    if (jQuery('#section-of_homepage_display input[value="static"]:checked').val() === undefined) { 
     jQuery('#section-of_homepage_display input[value="static"]').click(function() { 
      jQuery('.homepage_display').hide(400); 
      jQuery('.homepage_display_static').show(400); 
     }); 
    } 

    if (jQuery('#section-of_homepage_display input[value="static"]:checked').val() !== undefined) { 
     jQuery('.homepage_display_static').show(); 
    } 

}); 
+0

寻找.attr('checked')=='checked' –

+0

Hi @Diodeus感谢您的回应。现在有http://jsfiddle.net/MMVgp/,但是初始检查单选按钮是否被选中仍然不起作用。另外,如果单选按钮没有被选中,只运行'.click()'函数似乎也没有效果。谢谢! – Zach

回答

1

这里有一个的jsfiddle工作演示:http://jsfiddle.net/jessegavin/8ByKA/2/

jQuery(function() { 

    // This function handles the radio clicks. 
    function handleSelection() { 
     var duration = 400; 
     jQuery('.homepage_display').hide(duration); 
     if (this.value === "slideshow") { 
      jQuery('.homepage_display_slides').show(duration);  
     } else if (this.value === "static") { 
      jQuery('.homepage_display_static').show(duration);  
     } 
    } 

    // Hide all elements initially 
    // To prevent showing the non-selected items at first 
    jQuery('.homepage_display').hide(); 

    // Attach a click handler to the radios 
    // and trigger the selected radio 
    jQuery("#section-of_homepage_display :radio") 
     .click(handleSelection) 
     .filter(":checked").trigger("click"); 
}); 
+0

嗨@jessegavin非常感谢你的回应!这似乎很有效,除了已经选择了一个收音机选项时,你仍然可以点击它并且'.show()'持续时间仍然会触发(所以它基本上会崩溃并重新打开)。无论如何检查单选按钮是否被选中,只运行'.show()'函数的基础上?肯定比我以前的代码效率更高:)谢谢! – Zach