2013-03-04 147 views
0

看着這個jsFiddle,我的複選框永遠不會獲得checked屬性。這是一個非常簡單的測試,但我無法獲得顯示true的警報。複選框未被檢查

http://jsfiddle.net/ZLpHv/

<input type="checkbox" id="checky" /> 

$(document).ready(function() { 
    $("#checky").click(function() { 
     alert($(this).is("checked")); 
    }); 
}); 

爲什麼在兩種情況下,警報顯示false?爲什麼checked屬性從未被設置到複選框?我在這裏做錯了什麼?

+2

爲什麼downvote?請解釋一下,誰下降了? – 2013-03-04 15:47:29

回答

8

它實際上是:

$(this).is(":checked") 

和有約束力的改變事件更令其工作,如果它與鍵盤檢查:

$(document).ready(function() { 
    $("#checky").on('change', function() { 
     alert($(this).is(":checked")); 
    }); 
}); 
+0

+1哈哈,即使是相同的措辭。 :) – insertusernamehere 2013-03-04 15:46:24

+0

@insertusernamehere - 是的,有趣的是,有時候會發生這種情況! – adeneo 2013-03-04 15:47:21

+0

@adeneo是jQuery 1.6版本中的首選,但首選的方法是使用['.prop()'](http://api.jquery.com/prop/#prop1)。小提琴:http://jsfiddle.net/ZLpHv/4/ – 2013-03-04 15:50:06

2

你忘記了「:」。

alert($(this).is(":checked")); 
1
$(function() { 
    //checkbox 
    $("#terms").click(function(){ 
     //if this... 
     //alert("this")... 
     if($("#terms").is(':checked')) 
     {    
      alert("im checked"); 
     } 
    }); 
    //button 
    $("#buttonID").click(function(e){ 
     if(!$("#terms").is(':checked')) 
     { 
      alert("you did not check the agree to terms..."); 
      e.preventDefault(); 
     } 
    }); 
} 

你可以使用這個工作對我來說