2011-06-03 128 views
2

出於某種原因,下面的代碼不能正常工作:的onClick函數返回undefined

<input onclick="$(function(){ alert($(this).attr('checked')); })" name="step1[agree]" id="step1_agree" value="1" type="checkbox"> 

它告誡與undefined。我也嘗試做這樣的事情:

onclick="$(function(){ var chk=$(this); alert(chk.attr('id')); })" 

...但結果是相同的結果。我做錯了什麼,我該如何解決這個問題?

回答

5
<input onclick="alert($(this).attr('checked'));" name="step1[agree]" id="step1_agree" value="1" type="checkbox"> 

但一個更好的選擇是

<input name="step1[agree]" id="step1_agree" value="1" type="checkbox"> 

$('#step1_agree').click(function() { 
    alert($(this).attr('checked)); 
}); 
+1

請在前面加上''#你選擇 – mkilmanas 2011-06-03 11:29:40

+0

@mkilmanas - 感謝 – devmatt 2011-06-03 11:35:43

3

這應該工作。

onclick="alert(this.checked);" 
0

請參考unobtrusive javascript

您可以使用類似

$(function(){ 
    $("#step1_agree").click(function(){ 
     alert (this.checked); 
    }); 
}); 

$(function(){ });被炒魷魚一旦DOM已準備就緒。

您必須將所有事件處理程序分配在文檔準備就緒內。您可以使用id selectorclick event handler附加到所需的元素。要獲得檢查的屬性,您可以使用原生JavaScript代碼this.checked

1

不知道爲什麼要在這樣的一個函數進行包裝。它應該只是

onclick="alert($(this).attr('id'));"

2

請了解binding jQuery中。

 
$('#step1_agree').bind('click', function() { 
    alert(this.checked); 
}); 
0

看來你必須使用以下方法:

<script type="text/javascript"> 
    $(function(){ 
$('#step1_agree').click(function(){ 
alert('') 
}); 
}) 
</script>