2011-11-29 111 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