2010-08-17 48 views
4

我正在学习jquery,而且我很难运行以下非常简单的代码。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'); 
}); 

当我加载浏览器的页面......我得到的第一个警报当文档被加载时(所以我确信我至少使用了正确的库并且它正在被下载等)。

然而,当我点击我的按钮,我没有看到第二个警告,说“按钮被点击”

我缺少什么?

回答

3

click处理程序需要走你的$(document).ready内,以确保它势必在DOM准备好,并且该元素将保证可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

这是首先要了解 jQuery的:如果你想要一个事件,您的网页上工作 ,你应该把它 的$内(文件).ready() 函数。在页面内容加载之前,一旦DOM被加载,其中的所有内容将会加载 ,并加载 。

1

你可能要绑定的$(文件)。就绪()事件中的事件处理程序:

$(document).ready(function(){ 
    alert('document is ready'); 

    $('#testbutton').click(function(){ 
    alert('button clicked'); 
    }); 
}); 

这可以确保您的DOM脚本等被执行之前被加载。看看这是否能解决你的问题。

1

您还需要一个点击一个document.ready内结合,就像这样:

$(function(){  //short for $(document).ready(function(){ 
    alert('document is ready'); 
    $('#testbutton').click(function(){ 
    alert('button clicked'); 
    }); 
}); 

为什么呢?是选择器$('#testbutton')在选择器运行时未找到元素id="testbutton",因此它需要在页面中的元素之后或上面的document.ready处理程序中运行。