jQuery的点击功能不起作用
问题描述:
所以我有一个非常简单的代码形式和一键 使用jQuery我想,当用户点击该按钮将绑定一些行动,但由于某种原因,它不工作jQuery的点击功能不起作用
下面是代码
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<script>
$('#jallerysubmit').bind('click', function() {
alert('asd');
})
</script>
<form>
<input type="checkbox" name="box1">box1<br>
<input type="checkbox" name="box1">box2<br>
<input type="button" id="jallerysubmit" value="Proved">
</form>
</body>
</html>
请建议什么不对的代码,因为它不能正常工作,甚至也不会产生任何错误
答
你需要将其包装在一个document ready
处理程序。
<script>
$(function() {
$('#jallerysubmit').bind('click', function() {
alert('asd');
});
});
</script>
答
包括警报( “你好”);之后确保jQuery正常工作。然后在提交句柄的末尾添加一个返回false以确保页面在单击按钮时不会重新加载,也可以使用document.ready。见下文
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
alert("hello");
$('#jallerysubmit').bind('click', function() {
alert('asd');
return false;
});
});
</script>
<form>
<input type="checkbox" name="box1">box1<br>
<input type="checkbox" name="box1">box2<br>
<input type="button" id="jallerysubmit" value="Proved">
</form>
</body>
</html>
答
的DOM被加载之前的JavaScript代码将被执行的代码,所以用ID jallerysubmit
的元件不能被发现(它还不存在)。
@ sje397描述了一种非常常见的方式(至少在使用jQuery时)如何解决这个问题。另一种方法是把脚本在文档的末尾:在DOM存在之前的元素,因此选择不返回任何正在执行
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<form>
<input type="checkbox" name="box1">box1<br>
<input type="checkbox" name="box1">box2<br>
<input type="button" id="jallerysubmit" value="Proved">
</form>
<script>
$('#jallerysubmit').bind('click', function() {
alert('asd');
});
</script>
</body>
</html>
答
您的代码安装的处理程序,并没有应用处理器。把代码放在文档就绪处理程序中,它应该可以工作。您还可以使用click快捷方式进行简化。
<script>
$(function() {
$('#jallerysubmit').click(function() {
alert('asd');
});
});
</script>
答
最好的做法是使用外部.js文件,例如的script.js:
$(document).ready(function() {
yourFunction();
});
function yourFunction() {
$('#jallerysubmit').click(function() {
alert('asd');
});
}
,并在标签头导入它在你的HTML文件:
<script type="text/javascript" src="script.js"></script>
答
始终使用jQuery中的功能
(document).ready(function(){//ur jquery codes});
或
$().ready(function(){//ur jquery codes});
或
$.noConflict();
jQuery(document).ready(function($){//ur codes});
一旦页面的DOM是准备好上述功能加载启动。所以我建议jquery爱好者在这段代码中写下他们的魔法代码
谢谢。它现在的作品 – 2010-12-19 14:45:02
@Tomas:不客气。 – sje397 2010-12-19 14:45:49