2013-03-04 154 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(); 
     } 
    }); 
} 

你可以使用这个工作对我来说