`
JavaCrazyer
  • 浏览: 2990830 次
  • 性别: Icon_minigender_1
  • 来自: 河南
社区版块
存档分类

JQuery简单学习(4)——JQuery事件

阅读更多

 

jQuery 是为事件处理特别设计的。

————————————————————
jQuery 事件函数
jQuery 事件处理函数是 jQuery 中的核心函数。

事件处理函数是当 HTML 中发生事件时自动被调用的函数。由“事件”(event)“触发”(triggered)是经常被用到的术语。
————————————————————
在您 <head> 中
由于 jQuery 是为事件处理特别设计的,通常是把 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 type="button">Click me</button>
</body>

</html>
 在上面的例子中,定义了一个处理 HTML 按钮的点击事件的 click 函数:
$("button").click(function() {..some code... } )
 click 函数内部的代码隐藏所有 <p> 元素:
click 函数内部的代码隐藏所有 <p> 元素:
 所有事件函数都在文档自身的“事件处理器”内部进行定义:
$(document).ready(function() {..some code...} )
 ————————————————————
单独文件中的函数
如果您的网站包含许多页面,并且您希望您的 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>
 
 ————————————————————
 jQuery 名称冲突

jQuery 使用 $ 符号作为 jQuery 的简介方式。

某些其他 JavaScript 库中的函数(比如 Prototype)同样使用 $ 符号。

jQuery 使用名为 noConflict() 的方法来解决该问题。

var jq=jQuery.noConflict(),帮助您使用自己的名称(比如 jq)来代替 $ 符号。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
var $jq=jQuery.noConflict();
$jq(document).ready(function(){
  $jq("button").click(function(){
    $jq("p").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
  ————————————————————
结论
由于 jQuery 是为处理 HTML 事件而特别设计的,那么当您遵循以下原则时,您的代码会更恰当且更易维护:

  • 把所有 jQuery 代码置于事件处理函数中 
  • 把所有事件处理函数置于文档就绪事件处理器中 
  • 把 jQuery 代码置于单独的 .js 文件中 
  • 如果存在名称冲突,则重命名 jQuery 库 
   ————————————————————
jQuery 事件
下面是 jQuery 中事件函数的一些例子:
Event 函数 绑定函数至 $(document).ready(function)

文档的就绪事件

(当 HTML 文档就绪可用)

$(selector).click(function) 被选元素的点击事件 $(selector).dblclick(function) 被选元素的双击事件 $(selector).focus(function) 被选元素的获得焦点事件 $(selector).mouseover(function) 被选元素的鼠标悬停事件

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics