Jquery 简明教程

jQuery - Event Handling

没有与它相关联的事件是无法想象的。事件是构建交互式网页的机制。jQuery 足够智能,可以处理 HTML 页面上产生的任何事件。首先让我们尝试了解什么是事件。

Any modern web application can’t be imagined without an event associated with it. Events are the mechanism to build an interactive web page. jQuery is smart enough to handle any event generated on an HTML page. First let’s try to understand what is an event.

What are jQuery Events?

jQuery 事件是由 jQuery(JavaScript)可以检测到的操作的结果。当触发这些事件时,您可以使用自定义函数对事件执行您想要做的任何操作。这些自定义函数称为 Event Handlers

A jQuery Event is the result of an action that can be detected by jQuery (JavaScript). When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions are called Event Handlers.

jQuery 库提供了处理所有 DOM 事件的方法,并且比 JavaScript 中可用的方法大大简化了完整的事件处理。

The jQuery library provides methods to handle all the DOM events and make complete event handling considerably easier than what we have available in JavaScript.

以下是某些常见事件的示例 −

Following are the examples of some common events −

  1. A mouse click

  2. A web page loading

  3. Taking mouse over an element

  4. Submitting an HTML form

  5. A keystroke on your keyboard, etc.

下表列出了一些重要的 DOM 事件。

The following table lists some of the important DOM events.

Mouse Events

Keyboard Events

Form Events

Document Events

click

keypress

submit

load

dblclick

keydown

change

resize

hover

keyup

select

scroll

mousedown

blur

unload

mouseup

focusin

ready

此章节仅介绍了几个事件方法和属性。有关所有 jQuery 事件方法和属性的完整参考,您可以访问 jQuery Events Reference

This chapter coveres only few event methods and properties, For a complete reference of all the jQuery Event Methods and Properties, you can go to through jQuery Events Reference.

jQuery Event Binding Syntax

当您想单击 HTML 文档中的 <div> 然后对该单击执行某些操作时,请考虑这种情况。要实现此目的,您需要使用 jQuery click 事件绑定 <div> 元素,然后针对单击事件定义一个操作。

Consider a situation when you want to click a <div> in an HTML document and then you want to perform some action against this click. To achieve this you will have to bind a jQuery click event with the <div> element and then define an action against the click event.

Following is jQuery syntax to bind a click event with all the <div> elements available in an HTML document:

$("div").click();

下一步是针对单击事件定义一个操作。以下是可以定义一个函数的语法,该函数将在 click 事件触发后执行。此函数称为 jQuery Event Handler

The next step is to define an action against the click event. Following is the syntax to define a function which will be executed when click event will be fired. This function is called jQuery Event Handler

$("div").click(function(){
   // jQuery code goes here
});

Following is another syntax to bind a click event with any of the DOM elements:

$("div").bind('click', function(){
   // jQuery code goes here
});

jQuery Event Examples

jQuery click Event

以下是一个绑定 click 事件的示例,其中在单击任何 div 时都会显示一个警报框。尝试单击图标 以运行以下 jQuery 代码:

Following is an example to bind a click event with <div> where an alert box is displayed whenever you click on any of the divs. Try to click the icon to run the following jQuery code:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").click(function(){
         alert('Hi there!');
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
   <p>Click on any of the squares to see the result:</p>

   <div>One</div>
   <div>Two</div>
   <div>Three</div>
</body>
</html>

jQuery dblclick Event

Let’s re-write the above code to bind a dblclick event with <div> where an alert box is displayed whenever you double click on any of the divs.

Let’s re-write the above code to bind a dblclick event with <div> where an alert box is displayed whenever you double click on any of the divs.

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").dblclick(function(){
         alert('Hi there!');
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
   <p>Double click on any of the squares to see the result:</p>

   <div>One</div>
   <div>Two</div>
   <div>Three</div>
</body>
</html>

jQuery mouseenter Event

以下是一个绑定 mouseenter 事件的示例,其中在将光标移入任何 div 时都会显示一个警报框。

Following is an example to bind a mouseenter event with <div> where an alert box is displayed whenever you bring cursor over any of the divs.

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").mouseenter(function(){
         alert('Cursor is in!');
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
   <p>Bring cursor over any of the squares to see the result:</p>

   <div>One</div>
   <div>Two</div>
   <div>Three</div>
</body>
</html>

jQuery mouseleave Event

以下是一个绑定 mouseleave 事件的示例,其中在将光标移出 div 时会显示一个警报框。

Following is an example to bind a mouseleave event with <div> where an alert box is displayed whenever you take cursor out of the div.

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").mouseleave(function(){
         alert('Curosr is out!');
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
   <p>Take cursor out any of the squares to see the result:</p>

   <div>One</div>
   <div>Two</div>
   <div>Three</div>
</body>
</html>

jQuery mousedown Event

以下是一个绑定 mousedown 事件的示例,其中在左键、中键或右键按在任何 div 上时都会显示一个警报框。

Following is an example to bind a mousedown event with <div> where an alert box is displayed whenever the left, middle or right mouse button is pressed down over any of the divs.

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").mousedown(function(){
         alert('Mouse button is down!');
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
   <p>Press mouse button down over any of the squares to see the result:</p>

   <div>One</div>
   <div>Two</div>
   <div>Three</div>
</body>
</html>

jQuery mouseup Event

以下是一个绑定 mouseup 事件的示例,其中在左键、中键或右键在任何 div 上释放时都会显示一个警报框。

Following is an example to bind a mouseup event with <div> where an alert box is displayed whenever the left, middle or right mouse button is released over any of the divs.

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").mouseup(function(){
         alert('Mouse button is released!');
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
   <p>Release mouse button over any of the squares to see the result:</p>

   <div>One</div>
   <div>Two</div>
   <div>Three</div>
</body>
</html>

jQuery Event Object

Whenever a jQuery event is fired, jQuery passes an Event Object to every event handler function.The event object provides various useful information about the event.

Whenever a jQuery event is fired, jQuery passes an Event Object to every event handler function.The event object provides various useful information about the event.

The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed.

以下事件属性/特性可以以与平台无关的方式访问且是安全的 −

The following event properties/attributes are available and safe to access in a platform independent manner −

Property

Description

altKey

Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.

ctrlKey

Set to true if the Ctrl key was pressed when the event was triggered, false if not.

data

The value, if any, passed as the second parameter to the bind() command when the handler was established.

keyCode

For keyup and keydown events, this returns the key that was pressed.

metaKey

Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs.

pageX

For mouse events, specifies the horizontal coordinate of the event relative from the page origin.

pageY

For mouse events, specifies the vertical coordinate of the event relative from the page origin.

relatedTarget

For some mouse events, identifies the element that the cursor left or entered when the event was triggered.

screenX

For mouse events, specifies the horizontal coordinate of the event relative from the screen origin.

screenY

For mouse events, specifies the vertical coordinate of the event relative from the screen origin.

shiftKey

Set to true if the Shift key was pressed when the event was triggered, false if not.

target

Identifies the element for which the event was triggered.

timeStamp

The timestamp (in milliseconds) when the event was created.

type

For all events, specifies the type of event that was triggered (for example, click).

which

For keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right).

Example

以下示例说明了不同的方块单击如何给出不同的坐标。

Following is an example to show how different square clicks give different coordinates.

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").click(function(eventObj){
         alert('Event type is ' + eventObj.type);
         alert('pageX : ' + eventObj.pageX);
         alert('pageY : ' + eventObj.pageY);
         alert('Target : ' + eventObj.target.innerHTML);
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
   <p>Click on any of the squares to see the result:</p>

   <div>One</div>
   <div>Two</div>
   <div>Three</div>
</body>
</html>

this Keyword in Event Handler

很多情况下,在事件处理程序中使用 this 关键字是非常容易的。此关键字表示触发该事件的 DOM 元素。

Many times it becomes very easy to make use of this keyword inside an event handler. This keyword represents a DOM element which triggers the event.

以下示例将显示所单击 <div> 的内容:

Following example will show the content of the clicked <div>:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("div").click(function(){
         alert($(this).text());
      });
   });
</script>
<style>
   div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
   <p>Click on any of the squares to see the result:</p>

   <div>One</div>
   <div>Two</div>
   <div>Three</div>
</body>
</html>

Removing Event Handlers

通常,一旦建立一个事件处理程序,它将在整个页面的生命周期中保持有效。有时,您可能需要移除事件处理程序。

Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.

jQuery 提供 unbind() 命令来移除现有的事件处理程序。unbind() 的语法如下所示 -

jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows −

selector.unbind(eventType, handler)

or

selector.unbind(eventType)

以下是参数的描述 -

Following is the description of the parameters −

  1. eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.

  2. handler − If provided, identifies the specific listener that’s to be removed.

jQuery Events Reference

您可以在以下页面获得所有 jQuery 事件方法和属性的完整参考: jQuery Events Reference

You can get a complete reference of all the jQuery Event Methods and Properties at the following page: jQuery Events Reference.