javascript jQuery 侦听器单击不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7540632/
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
jQuery listener click not working
提问by Axel Latvala
So I have this code that shouldlisten for a click on #button but it won't work, and is driving me crazy!
所以我有这段代码应该听#button上的点击,但它不起作用,让我发疯!
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$('#button').click(function() {
alert('OK!');
});
</script>
and the HTML:
和 HTML:
<input id="button" type="button" value="OK" />
This is strange. Any help is welcome!
这很奇怪。欢迎任何帮助!
回答by Ujjwal Manandhar
Write your code inside document.ready function
在 document.ready 函数中编写代码
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#button').click(function() {
alert('OK!');
});
});
</script>
OR
<script type="text/javascript">
function on_click() {
alert("OK !!");
}
$(document).ready(function() {
$("#button").click(on_click);
});
</script>
hope you get some idea from this
希望你能从中得到一些想法
回答by Chris Pietschmann
Here's what the code should look like:
代码如下所示:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script type="text/javascript">
// Now that jquery is include, place the code to wire up the button here
$(function(){
// Once the document.onload event fires, attach the click
// event handler for the button
$('#button').click(function() {
alert('OK!');
});
});
</script>
<input id="button" type="button" value="OK" />
Here's the jquery documentation that relates to this: http://docs.jquery.com/How_jQuery_Works
这是与此相关的 jquery 文档:http: //docs.jquery.com/How_jQuery_Works