jQuery 事件函数
jQuery 事件处理方法是 jQuery 中的核心函数。
事件处理程序指的是当 HTML 中发生某些事件时所调用的方法。
通常会把 jQuery 代码放到 <head>部分的事件处理方法中:
实例
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head> <body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body> </html>
在上面的例子中,当按钮的点击事件被触发时会调用一个函数:
$("button").click(function() {..some code... } )
该方法隐藏所有 <p> 元素:
$("p").hide();
单独文件中的函数
如果您的网站包含许多页面,并且您希望您的 jQuery 函数易于维护,那么请把您的 jQuery 函数放到独立的 .js 文件中。
当我们在教程中演示 jQuery 时,会将函数直接添加到 <head> 部分中。不过,把它们放到一个单独的文件中会更好,就像这样(通过 src 属性来引用文件):
实例
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="my_jquery_functions.js"></script>
</head>