我正在学习 jquery,但运行以下极其简单的代码时遇到困难。
我的 HTML 看起来像:
<html>
<head>
<title>JQUERY</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<input type="button" id="testbutton" value="test" />
</body>
我的 script.js 看起来像这样:
$(document).ready(function(){
alert('document is ready');
});
$('#testbutton').click(function(){
alert('button clicked');
});
当我在浏览器中加载页面时...加载文档时我收到第一个警报(因此我确信我至少使用了正确的库并且正在下载它等)。
但是,当我单击按钮时,我没有看到第二个警告“按钮已被单击”
我错过了什么?
最佳答案
click
处理程序需要进入您的 $(document).ready
内部,以确保在 DOM 准备好时绑定(bind)它,并且保证元素可用于 Javascript 处理:
$(document).ready(function(){
alert('document is ready');
// bind a click handler to #testbutton when the DOM has loaded
$('#testbutton').click(function(){
alert('button clicked');
});
});
来自documentation :
This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
关于JQuery 按钮不显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498429/