2011-06-23 84 views
2

我很困惑這個代碼的自我解釋什麼它應該做的事,但它不會做在這裏jquery單選按鈕沒有切換?

<input name="property" type="radio" checked value="1" />Station Masters House 
<input name="property" type="radio" value="2" />Railway Carriage 

<br><br> 
<div id="fillin">press</div> 

$("#fillin").click(function() {  
     if ($('input[name=property]').val() == "1") 
     { 

      alert($('input[name=property]').val()); 

     } else if ($('input[name=property]').val() == "2") { 

      alert($('input[name=property]').val()); 
     } 


    }); 

例如

http://jsfiddle.net/BFf5H/40/

回答

4

input[name=property].length === 2 ...因此,.val()韓元」工作。 (.val拉取DOM中第一個元素的值,它找到與請求的選擇器匹配的元素,但<select multiple>元素除外)。

嘗試使用input[name=property]:checked代替。

$("#fillin").click(function() {  
    if ($('input[name=property]:checked').val() == "1") 
    { 

     alert($('input[name=property]:checked').val()); 

    } else if ($('input[name=property]:checked').val() == "2") { 

     alert($('input[name=property]:checked').val()); 
    } 


}); 

更重要的是,緩存你需要的東西,所以你只打了DOM(或在這種情況下,jQuery的高速緩存)一次:

$("#fillin").click(function() { 
    var val = $('input[name=property]:checked').val(); 
    if (val == "1") { 
     alert(val); 
    } else if (val == "2") { 
     alert(val); 
    } 
}); 
1

你應該做的

if ($('input[name=property]:checked').val() == "1")