Events in jquery

Source: Internet
Author: User

Event

Because JavaScript runs in single-threaded mode in the browser, after the page is loaded, once all the JavaScript code on the page has been executed, you can only rely on triggering events to execute the JavaScript code.

After the browser receives the user's mouse or keyboard input, the corresponding event is automatically triggered on the corresponding DOM node. If the node is already bound to the corresponding JavaScript handler, the function is called automatically.

Because the code for different browser binding events is not the same, so using jquery to write code that masks differences in different browsers, we always write the same code.

For example, let's say we use jquery to bind an event when a user clicks on a hyperlink click :

<a id="test-link" href="#0">点我试试</a> * */// 获取超链接的jQuery对象:var a = $(‘#test-link‘);a.on(‘click‘, function () { alert(‘Hello!‘);});

Measured: I'll try.

onmethod is used to bind an event, we need to pass in the event name and the corresponding handler function.

Another simpler way to do this is to call the click() method directly:

a.click(function () {    alert(‘Hello!‘);});

The two are completely equivalent. We usually use the following notation.

The events that jquery can bind mainly include:

Mouse events

Click: trigger when mouse clicks, DblClick: Trigger when mouse double-click, MouseEnter: Trigger when Mouse enters, MouseLeave: trigger When mouse moves out, MouseMove: trigger when mouse moves inside Dom; Hover: Triggers two functions when mouse enters and exits, equivalent to MouseEnter plus mouseleave.

Keyboard events

Keyboard events only work on the DOM of the current focus, usually the <input> and <textarea> .

KeyDown: Triggered when the keyboard is pressed, KeyUp: triggered when the keyboard is released, KeyPress: Triggered once the key is pressed.

Other events

Focus: Triggers when the DOM gets focus, Blur: Triggers when the DOM loses focus, <input> change: triggers when, <select> or <textarea> the content changes, and <form> submits: triggers when commit; Ready: Fires when the page is loaded and the DOM tree finishes initializing.

Where ready only the object is used document . Because the ready event fires after the DOM finishes initializing and fires only once, it is ideal for writing additional initialization code. Assuming we want to bind an event to a <form> form submit , the following code does not have the expected effect:

<html><head>    <script> // 代码有误: $(‘#testForm).on(‘submit‘, function () { alert(‘submit!‘); }); </script></head><body> <form id="testForm"> ... </form></body>

Since JavaScript is executing at this time, the <form> browser has not yet been loaded, so it $(‘#testForm) returns and [] does not bind events to any DOM.

So our own initialization code must be placed in the document object's ready event to ensure that the DOM is initialized:

<html><head>    <script> $(document).on(‘ready‘, function () { $(‘#testForm).on(‘submit‘, function () { alert(‘submit!‘); }); }); </script></head><body> <form id="testForm"> ... </form></body>

There is no problem in writing this. Because the associated code executes after the DOM tree is initialized.

Because ready event usage is very common, this can be simplified:

$(document).ready(function () {    // on(‘submit‘, function)也可以简化:    $(‘#testForm).submit(function () { alert(‘submit!‘); });});

It can even be simplified to:

$(function () {    // init...});

The above notation is the most common. If you encounter $(function () {...}) the form, keep in mind that this is the document object's ready event handler function.

The event handlers can be bound repeatedly, and they will be executed in turn:

$(function () {    console.log(‘init A...‘);});$(function () { console.log(‘init B...‘);});$(function () { console.log(‘init C...‘);});
Event arguments

Some events, such as mousemove and keypress , we need to get the mouse position and key values, otherwise listening to these events is meaningless. All events are passed Event into the object as arguments, and more information can be obtained from the Event object:

$(function () {    $(‘#testMouseMoveDiv‘).mousemove(function (e) { $(‘#testMouseMoveSpan‘).text(‘pageX = ‘ + e.pageX + ‘, pageY = ‘ + e.pageY); });});

Effect measurement:

MouseMove

Move mouse in this area try Unbinding

An event that has been bound can be unbound by off(‘click‘, function) implementing:

function hello() {    alert(‘hello!‘);}a.click(hello); // 绑定事件// 10秒钟后解除绑定:setTimeout(function () { a.off(‘click‘, hello);}, 10000);

It is important to note that the following notation is not valid:

// 绑定事件:a.click(function () {    alert(‘hello!‘);});// 解除绑定:a.off(‘click‘, function () { alert(‘hello!‘);});

This is because two anonymous functions are identical, but they are two different function objects and off(‘click‘, function () {...}) cannot remove the first anonymous function that has been bound.

To achieve the removal effect, you can use the one-time off(‘click‘) removal click of all handler functions for the bound event.

Similarly, a parameterless call off() removes all of the bound event handler functions at once.

Event Trigger conditions

One problem to note is that the triggering of an event is always caused by a user action. For example, we monitor the contents of a text box to change:

var input = $(‘#test-input‘);input.change(function () { console.log(‘changed...‘);});

The event is triggered when the user enters in the text box change . However, if you use JavaScript code to change the value of the text box, the event will not be triggered change :

$(‘#test-input‘);input.val(‘change it!‘); // 无法触发change事件

There are times when we want to trigger change an event with code that directly invokes a parameterless change() method to trigger the event:

$(‘#test-input‘);input.val(‘change it!‘);input.change(); // 触发change事件

input.change()Equivalent input.trigger(‘change‘) , it is trigger() shorthand for the method.

Why do we want to trigger an event manually? If we don't do this, we'll have to write two identical codes in a lot of times.

Browser security Restrictions

In a browser, some JavaScript code can be executed only when triggered by a user, for example, a window.open() function:

// 无法弹出新窗口,将被浏览器屏蔽:$(function () {    window.open(‘/‘);});

These "sensitive code" can only be triggered by user actions:

 var button1 = $ (var button2 = $ ( ' #testPopupButton2 '); function popuptestwindow () {window.open (function  () {Popuptestwindow ();}); Button2.click (function  () { //does not immediately execute Popuptestwindow (), executes after 100 milliseconds: SetTimeout (Popuptestwindow, 100);});  

When the user clicks button1 , the click event is triggered, due to popupTestWindow() click execute within the event handler function, which is allowed by the browser, and button2 the event is click not immediately executed popupTestWindow() , deferred execution popupTestWindow() will be blocked by the browser.

Effect measurement:

Events in jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.