Home Web Front-end JS Tutorial Summary of jQuery event usage examples_jquery

Summary of jQuery event usage examples_jquery

May 16, 2016 pm 04:38 PM
jquery event usage

This article summarizes the usage of events in jQuery in detail with examples, which is a good reference value for learning jQuery. Share it with everyone for your reference. The specific usage is as follows:

1. Bind events to elements through method names:

$('li').click(function(event){})

Copy after login

2. Bind events to elements through the bind method:

$('li')
 .bind('click',function(event){})
 .bind('click',function(event){}) 
Copy after login
Copy after login

It can be seen that through bind, multiple events can be bound to elements.

3. Event namespace

Why do you need an event namespace?

→Suppose, first bind 2 click events to the li element.

$('li')
 .bind('click',function(event){})
 .bind('click',function(event){}) 
Copy after login
Copy after login

→Now we need to log out one of the click events, which may be written like this:

$('li').unbind('click')
Copy after login

But in this way, all click events in our li are logged out, which is not what we want. Using the event namespace can solve this problem. The reason why the event namespace is needed is because it provides convenience for us when logging off events.

How to use event namespace?
→When binding an event to an element, add the namespace after the event name, conforming to the format: event name.namespace name.

$('li')
 .bind('click.editMode',function(event){})
 .bind('click.displayMode',function(event){}) 
Copy after login

→When logging out of an event, you can write like this:

$('li').unbind('click.editMode')

Copy after login

4. Types of events

blur
change
click
dblclick
error
focus
focusin
focusout
keydown
keypress
keyup
load
mousedown
mouseenter
mouseleave
mousemove
mouseout
moseover
mouseup
ready
resize
scroll
select
submit
unload

5.one method

Used to create a one-time event. Once this event is executed once, it will be automatically deleted.

$("p").one("click",function(){
 $(this).animate({fontSize: "+=6px"});
})
Copy after login

6. Delete events

//先给元素添加事件
$("p").click(function(){
 $(this).slideToggle();
})
//再把元素的事件删除
$("button").click(function(){
 $("p").unbind();
})

Copy after login

7.Event attribute

Actually, it is a global property of jquery, jQuery.Event. Whenever an event is triggered, an Event object instance is passed to the Event Handler.

Events can be created and triggered through the Event constructor.

var e = jQueery.Event("click")
jQuery("body").trigger(e);

Copy after login

You can even pass an anonymous object in the Event through the constructor.

var e = jQuery.Event("keydown", {keyCode : 64});
jQuery("body").trigger(e);

Copy after login

When used, obtain the value of the anonymous object through event.data.KeyCode.

You can pass anonymous objects in Event through the constructor of jQuery.Event. Not only that, anonymous objects can also be passed through events.

$("p").click({param1 : "Hello", param2 : "World"}, someFunction);
function someFunction(event){
 alert(event.data.param1);
 alert(event.data.param2);
}
Copy after login

It can be seen that the key of the anonymous object can be obtained through event.data.

Through Event object instances, you can also get other aspects of information, such as:

$("p").click(function(event){
 alert(event.target.nodeName);
})
Copy after login

Above, get the name of the element that triggered the event through event.target.nodeName.

Other properties of jQuery.Event include:

altKey True if the alt key is pressed. In Mac keyboards, the alt key is marked Option
ctrKey ctrl key is pressed
shiftKey Shift key is pressed
currentTarget the current element in the bubbling stage
data
metaKey Generally the Meta key is Ctrl, but on Mac it is the Command key
The horizontal coordinate of the cursor relative to the origin of the page during pageX mouse event
pageY The vertical coordinate of the cursor relative to the origin of the page during mouse event
relatedTarget The element that the cursor leaves or enters when the mouse event is triggered
The horizontal coordinate of the cursor relative to the screen origin during screenX mouse event
screenY The vertical coordinate of the cursor relative to the origin of the screen during mouse events
result returns the most recent non-undefined value from the previous event handler
target element that triggers the event
timestamp The timestamp in milliseconds when the jQuery.Event instance was created
type event type, such as click
which If it is a keyboard event, it represents the number of the key. If it is a mouse event, it records whether the left button, middle button or right button was pressed

8.Event method

event.preventDefault() prevents default behavior
event.stopPropgation() stops "bubbling", that is, stops propagating further up the DOM
event.stopImmediatePropagation() stops further propagation of all events
event.isDefaultPrevented()
event.isPropgationStopped()
isImmediatePropgagationStopped()

9.live method and on method

This method allows us to create events for elements that don’t yet exist. The difference from the bind method is that it can bind events to all matching elements, and the settings are those elements that do not yet exist and need to be dynamically created. Moreover, the live method does not necessarily need to be placed in the $(function(){}) ready handler. After jQuery 1.7, it was changed to the on method.

$("p").on("click", function(){
 alert("hello");
})
Copy after login

If you want to cancel event registration:

$("button").click(function(){
 $("p").off("click");
})
Copy after login

10.trigger method

The trigger method can be used when we want to manually trigger an event bound to an element.

$("#foo").on("click",function(){
 alert($(this).text());
})
$("#foo").trigger("click");

Copy after login

还可以在绑定事件的时候出传入形参,在trigger事件的时候传入实参。

$("#foo").on("custom", function(event, param1, param2){
 alert(param1 + "\n" + param2)
})
$("#foo").trigger("custom",["Custom","Event"]);

Copy after login

trigger触发由jQuery.Event创建的实例:

var event = jQuery.Event("logged");
event.user = "foo";
event.pass = "bar";
$("body").trigger(event);

Copy after login

甚至可以在trigger触发方法的时候传入匿名对象:

$("body").trigger({
 type: "logged",
 user: "foo",
 pass: "bar"
});
Copy after login

如果想停止触发事件的传播,可通过jQuery.Event实例的stopPropgation()方法,或在任何事件中返回false。

11.triggerHandler方法

triggerHandler方法与trigger方法的不同之处在于:triggerHandler方法不会执行元素的默认事件,也不会"冒泡"。

//给一个元素绑定一个focus事件
$("input").focus(function(){
 $("<span>Focused</span>").appendTo("#id").fadeOut(1000);
})
//用triggerHandler触发
$("#id").click(function(){
 $("input").triggerHandler("focus");//不会触发focus的默认行为,即进入文本框
})
//用trigger触发
$("#id").click(function(){
 $("input").trigger("focus");//同时触发foucs的默认行为和绑定行为
})

Copy after login

12.事件冒泡和事件委托

什么是事件冒泡?

有这么一段代码。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
 <div>
  <p><a href="#foo"><span>I am a Link!</span></a></p>
  <p><a href="#bar"><b><i>I am another Link!</i></b></a></p>
 </div>
</body>
</html>

Copy after login

现在,给该页面所有的元素绑定click事件,包括window和document。

  $(function () {
   $('*').add([document, window]).on('click', function(event) {
    event.preventDefault();
    console.log(this);
   });
  });
Copy after login

当单击页面任何元素,单击事件会从当前元素开始,向上一级元素传播,直到最顶级元素,这里是window。

如何阻止事件冒泡?

显然,通常只希望在某个特定元素发生特定的事件,不希望事件冒泡的发生。这时候我们可以针对某个特定元素绑定事件。

  $(function () {
   $('a').on('click', function(event) {
    event.preventDefault();
    console.log($(this).attr('href'));
   });
  });
Copy after login

以上,只为a绑定了click事件,无它。

如何有效利用事件冒泡?

在jquery中,事件委托却很好地利用了事件冒泡。

<html>
<body>
<div id="container">
 <ul id="list">
  <li><a href="http://domain1.com">Item #1</a></li>
  <li><a href="/local/path/1">Item #2</a></li>
  <li><a href="/local/path/2">Item #3</a></li>
  <li><a href="http://domain4.com">Item #4</a></li>
 </ul>
</div>
</body>
</html>

Copy after login

现在,我们想给现有li中的a标签绑定事件,这样写:

$( "#list a" ).on( "click", function( event ) {
 event.preventDefault();
 console.log( $( this ).text() );
});

Copy after login

但是,如果又在现有的ul中添加新的li和a,那情况又如何呢?

$( "#list" ).append( "<li><a href='http://newdomain.com'>Item #5</a></li>" );

Copy after login

结果,点击新添加的li中的a,什么都没有发生。那么,如何为动态添加的元素绑定事件呢?

如果我们能把事件绑定到a的父级元素,那在父级元素内生成的子级动态元素,也会有绑定事件的行为。

$( "#list" ).on( "click", "a", function( event ) {
 event.preventDefault();
 console.log( $( this ).text() );
});
Copy after login

以上,我们把click事件绑定到a的父级元素id为list的ul上,on方法中的第二个参数,这里是a,是事件真正的执行者。具体过程如下:
→点击某个a标签
→根据事件冒泡,触发了a的父级元素ul的click事件
→而事件真正的执行者是a

事件委托允许我们把事件绑定到父级元素,这相当于给所有的子级元素绑定了事件,不管这个子级元素是静态的、还是动态添加的。

13.toggle方法

允许我们依次执行多个事件,当执行完最后一个事件后,再执行第一个事件。

$('img[src*=small]').toggle({
 function(){},
 function(){},
 function(){}
});

Copy after login

14.mouseenter和mouseleave方法

$(element).mouseenter(function(){}).mouseleave(function(){})

Copy after login

15.hover方法

$("p").hover(function(){
 $("p").css("background-color","yellow");
 },function(){
 $("p").css("background-color","pink");
});

Copy after login

相信本文所述对大家的jQuery程序设计有一定的借鉴价值。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Detailed explanation and usage introduction of MySQL ISNULL function Detailed explanation and usage introduction of MySQL ISNULL function Mar 01, 2024 pm 05:24 PM

The ISNULL() function in MySQL is a function used to determine whether a specified expression or column is NULL. It returns a Boolean value, 1 if the expression is NULL, 0 otherwise. The ISNULL() function can be used in the SELECT statement or for conditional judgment in the WHERE clause. 1. The basic syntax of the ISNULL() function: ISNULL(expression) where expression is the expression to determine whether it is NULL or

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Correct usage of POST request in PHP Correct usage of POST request in PHP Mar 27, 2024 pm 03:15 PM

The use of POST requests in PHP is a common operation in website development. Data can be sent to the server through POST requests, such as form data, user information, etc. Proper use of POST requests can ensure data security and accuracy. The following will introduce the correct usage of POST requests in PHP and provide specific code examples. 1. Basic principles of POST requests in PHP In PHP, the data submitted through the POST method can be obtained by using the $_POST global variable. The POST method converts the form number into

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles