javascript onClick 函数返回未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6226430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
onClick function returns undefined
提问by kusanagi
For some reason, the following code does not work properly:
出于某种原因,以下代码无法正常工作:
<input onclick="$(function(){ alert($(this).attr('checked')); })" name="step1[agree]" id="step1_agree" value="1" type="checkbox">
It alerts with undefined
. I have also tried doing something like this:
它发出警报undefined
。我也试过做这样的事情:
onclick="$(function(){ var chk=$(this); alert(chk.attr('id')); })"
... but ends up with the same result. What am I doing wrong and how can I fix this?
...但最终结果相同。我做错了什么,我该如何解决?
回答by devmatt
<input onclick="alert($(this).attr('checked'));" name="step1[agree]" id="step1_agree" value="1" type="checkbox">
But a better option would be
但更好的选择是
<input name="step1[agree]" id="step1_agree" value="1" type="checkbox">
$('#step1_agree').click(function() {
alert($(this).attr('checked));
});
回答by Jishnu A P
This should work.
这应该有效。
onclick="alert(this.checked);"
回答by amustill
回答by epascarello
Not sure why you are wrapping it in a function like that. It should just be
不知道为什么要将它包装在这样的函数中。它应该只是
onclick="alert($(this).attr('id'));"
onclick="alert($(this).attr('id'));"
回答by rahul
Please refer to unobtrusive javascript
You can use something like
你可以使用类似的东西
$(function(){
$("#step1_agree").click(function(){
alert (this.checked);
});
});
$(function(){
});
gets fired once the DOM is ready.
$(function(){
});
一旦 DOM 准备就绪,就会被触发。
You must assign all event handlers inside document ready. You can use an id selector
to attach a click event handler
to the desired element. To get the checked attribute you can use the native javascript code this.checked
.
您必须在文档就绪内分配所有事件处理程序。您可以使用 anid selector
将 a 附加click event handler
到所需的元素。要获取已检查的属性,您可以使用本机 javascript 代码this.checked
。
回答by katrin
Seems you have to use the following:
似乎您必须使用以下内容:
<script type="text/javascript">
$(function(){
$('#step1_agree').click(function(){
alert('')
});
})
</script>