The foundation of jquery--Events

Source: Internet
Author: User

jquery Basics-Events Mouse events click and Dbclick events

The click Method listens for user clicks, and Dbclick listens for user double-clicking Operations, which are similar to two methods.
the Dbclick differs from the Click event :

The Click event trigger requires the following points:

    • The Click event is actually made up of 2 actions by MouseDown and MouseUp, so the clicked action is only triggered when you let go.

The following points are required for DblClick event triggering:
DblClick is also superimposed by 2 Click, so the DblClick event can only be triggered if the following conditions are met

    • Click when the mouse pointer is inside the element.
    • The mouse pointer is released inside the element.
    • The mouse pointer inside the element when the click, click the interval time, is system-determined.
    • When the mouse pointer is inside the element, it is released again.

method One: $ele. Click ()
Used to trigger events manually
method Two: $ele. Click (Handler (eventobject))

    <script type="text/javascript">        $(‘p‘).click(function(e) {            alert(e.target.textContent)        })        //this指向button元素        $("button:eq(1)").click(function() {            $(‘p‘).click() //指定触发绑定的事件        })    </script>

The E in function (e) is for the event, please refer to in Javascript/jquery what does (e) mean?. For example e.preventDefault , you can block out some of the original control's events and execute new events.

$(‘a‘).click(function(e) {    e.preventDefault();}

method Three: $ele. Click ([EventData], Handler (eventobject))
Used in accordance with method two, but can accept a data parameter, such processing is to solve the problem of data transfer under different scopes

<script type="text/javascript">    //不同函数传递数据    function data(e) {        alert(e.data) //1111    }    function a() {        $("button:eq(2)").click(1111, data)    }    a();
MouseDown and MouseUp events

The following points are required for MouseDown event triggering:

    • MouseDown emphasis is on the trigger
    • If you hold down the mouse on an element and drag the mouse away from the element and release the mouse button, this is still counted as the MouseDown event
    • MouseDown events can be triggered when any mouse button is pressed
    • Use the event object's which to distinguish the key, hit the left mouse button which value is 1, hit the mouse key which value is 2, the right mouse button to which the value is 3

The following points are required for MouseUp event triggering:

    • MouseUp stress is to let go of the trigger, and MouseDown is the opposite
    • MouseUp and MouseDown together are the Click event
    • If the user presses the mouse button on an element and drags the mouse away from the element, then releases the mouse button, which is still counted as the MouseUp event
    • Any mouse button can trigger the MouseUp event when it's off
    • Use the event object's which to distinguish the key, hit the left mouse button which value is 1, hit the mouse key which value is 2, the right mouse button to which the value is 3
MouseMove Events

The MouseMove event is triggered when the mouse pointer moves, even if it is a pixel

<script type="text/javascript">//绑定一个mousemove事件//触发后修改内容$(".aaron1").mousemove(function(e) {    $(this).find(‘p:last‘).html(‘移动的X位置:‘ + e.pageX)})</script>

MouseOver and Mouseout Events

To listen for a user's move-in move-out operation

<script type="text/javascript">    var n = 0;    //绑定一个mouseover事件    $(".aaron1 p:first").mouseover(function(e) {        $(".aaron1 a").html(‘进入元素内部,mouseover事件触发次数:‘ + (++n))    })</script>
MouseEnter and MouseLeave Events

the difference between MouseEnter events and MouseOver
The key point is: The bubbling way to deal with the problem

A simple example:
MouseOver For example:

<div class="aaron2">    <p>鼠标离开此区域触发mouseleave事件</p></div>

If the P element and the DIV element are bound to the MouseOver event, the mouse leaves the P element, but does not leave the DIV element when the result is triggered:

    1. P Element Response Event
    2. div element Response Event

The question here is why does Div get triggered? The reason is the event bubbling problem, p element triggered mouseover, he will always look up the parent element on the MouseOver event, if there is a full trigger

So under this scenario,jquery recommends that we use the MouseEnter event

The MouseEnter event is called only on the element that binds it, not on the descendant node.

<script type="text/javascript">    var i = 0;    $(".aaron2 p").mouseenter(function(e) {        $(".aaron2 a:first").html(‘mouseenter事件触发次数:‘ + (++i))    })    var n = 0;    $(".aaron2").mouseenter(function() {        $(".aaron2 a:last").html(‘mouseenter冒泡事件触发次数:‘ + (++n))    })</script>
Hover Events

Move the element on the move out to toggle its color change, generally through 2 event mates can be achieved, here with MouseEnter and MouseLeave, so as to avoid bubbling problem

$(ele).mouseenter(function(){     $(this).css("background", ‘#bbffaa‘); })$(ele).mouseleave(function(){    $(this).css("background", ‘red‘);})

However, this is a bit complicated and can be replaced with the hover method $(selector).hover(handlerIn, handlerOut) .

    • Handlerin (EventObject): event function that triggers execution when the mouse pointer enters an element
    • Handlerout (EventObject): event function that triggers execution when the mouse pointer leaves an element

As follows:

    $("p").hover(        function() {            $(this).css("background", ‘red‘);        },        function() {            $(this).css("background", ‘#bbffaa‘);        }    );
Focusin Events

You can use the Focusin method when an element, or any element within it, gets the focus

<script type="text/javascript">    //不同函数传递数据    function fn(e) {         $(this).val(e.data)    }    function a() {        $("input:last").focusin(‘慕课网‘, fn)    }    a();</script>

Or

<script type="text/javascript">    //input聚焦    //给input元素增加一个边框    $("input:first").focusin(function() {         $(this).css(‘border‘,‘2px solid red‘)    })</script>
Focusout Events

You can use the Focusout method when an element, or any element within it, loses focus

<script type="text/javascript">    //input失去焦点    //给input元素增加一个边框    $("input:first").focusout(function() {         $(this).css(‘border‘,‘2px solid red‘)    })</script>
Form event blur and Foucus events

The essential difference between them: whether to support bubbling processing
To give a simple example

<div>  <input type="text" /></div>

Where the INPUT element can trigger the focus () event

The div is the parent element of input, and it generates the Focusin () event when it contains an element input that triggers the focus event.

focus()在元素本身产生,focusin()在元素包含的元素中产生

Blur and Focusout are also so

<script type="text/javascript">$(".aaron").focus(function() {    $(this).css(‘border‘, ‘2px solid red‘)})$(".aaron1").focusin(function() {    $(this).find(‘input‘).val(‘冒泡捕获了focusin事件‘)})</script>
Change Event

<input>Elements, <textarea> and <select> elements are all can be selected to change the value of some

//监听input值的改变$(‘.target1‘).change(function(e) {    $("#result").html(e.target.value)});
Select Event

Select events can only be used for <input> elements and <textarea> elements

//监听input元素中value的选中//触发元素的select事件$("input").select(function(e){    alert(e.target.value)})$("#bt1").click(function(){    $("input").select();})//监听textarea元素中value的选中$(‘textarea‘).select(function(e) {    alert(e.target.value);});
Submit Event

By binding a <form> submit event on an element, the developer can listen to the behavior of the user's submission form

Behavior that can trigger the submit event specifically:

<input type="submit"><input type="image"><button type="submit">当某些表单元素获取焦点时,敲击Enter(回车键)

All of these operations can intercept the submit event.

Special attention is needed here:

The form element is the behavior of a default submission form, which, if handled by a submit, requires the browser's default behavior to be suppressed.
The traditional way is to invoke the event object e.preventDefault() to handle, jquery can be directly in the function of the end of the return to False can

jquery is handled as follows:

$("#target").submit(function(data) {    return false; //阻止默认行为,提交表单});

Example:

<div class="left">        <div class="aaron">            <form id="target1" action="test.html">                回车键或者点击提交表单:                 <input type="text" value="输入新的值" />                <input type="submit" value="Go" />            </form>        </div>        <div class="aaron">            <form id="target2" action="destination.html">                回车键或者点击提交表单,禁止浏览器默认跳转:                 <input type="text" value="输入新的值" />                <input type="submit" value="Go" />            </form>        </div>    </div>    <script type="text/javascript">    //回车键或者点击提交表单    $(‘#target1‘).submit(function(e) {        alert(‘捕获提交表达动作,不阻止页面跳转‘)    });    //回车键或者点击提交表单,禁止浏览器默认跳转:    $(‘#target2‘).submit(function() {        alert(‘捕获提交表达动作,阻止页面跳转‘)        return false;    });    </script>
Keyboard events KeyDown () and KeyUp () events

The KeyDown event is triggered when the keyboard is pressed

//直接绑定事件$elem.keydown( handler(eventObject) )//传递参数$elem.keydown( [eventData ], handler(eventObject) )//手动触发已绑定的事件$elem.keydown()

The KeyUp event is triggered when the keyboard has been loosened

KeyPress () Event

Binding the KeyDown event on the INPUT element will find a problem:

每次获取的内容都是之前输入的,当前输入的获取不到

KeyDown event trigger is not in the text box, if the text in the KeyDown event output text box, the text is triggered before the keyboard event, and the KeyUp event triggered when the entire keyboard event operation has been completed, obtained is triggered after the keyboard event text

When the browser captures the keyboard input, it also provides a keypress response, which is very similar to the KeyDown, please refer to the KeyDown section, specifically, the different points.

The main differences between KeyPress events and KeyDown and KeyUp

对中文输入法支持不好,无法响应中文输入无法响应系统功能键(如delete,backspace)由于前面两个限制,keyCode与keydown和keyup不是很一致

Word

KeyPress are primarily used to receive ANSI characters such as letters, numbers, and KeyDown and KeyUP event procedures can handle any keystroke that is not recognized by KeyPress. such as: function keys (F1-F12), edit keys, positioning keys, and any combination of these keys and keyboard shift keys.

Event bindings and binding on () multi-event bindings

Basic usage: .on( events [, selector ] [, data ] )
The most common:

$("#elem").click(function(){})  //快捷方式$("#elem").on(‘click‘,function(){}) //on方式

Multiple events bound to the same function

 $("#elem").on("mouseover mouseout",function(){ });

Multiple events bind different functions

$("#elem").on({    mouseover:function(){},      mouseout:function(){},});

Passing data to a handler

function greet( event ) {  alert( "Hello " + event.data.name ); //Hello 慕课网}$( "button" ).on( "click", {  name: "慕课网"}, greet );
Advanced usage of On ()

For their own processing mechanism, there is not only an on method, but also based on the evolution of the live method (after 1.7 is removed), delegate method and so on. The underlying implementation of these methods is also the on method, which is derived from the mechanism of another event mechanism delegate using on.

Delegation mechanism

.on( events [, selector ] [, data ], handler(eventObject) )

Example

<script type="text/javascript">//给body绑定一个click事件//没有直接a元素绑定点击事件//通过委托机制,点击a元素的时候,事件触发$(‘body‘).on(‘click‘, ‘a‘, function(e) {   alert(e.target.textContent)})</script>
Unload event Off () method

Binding 2 Events

$("elem").on("mousedown mouseup",fn)

Delete an event

$("elem").off("mousedown")

Delete all Events

$("elem").off("mousedown mouseup")

Shortcut to delete all events, there is no need to pass the event name, all events bound by the node are destroyed

$("elem").off()
Use of Event objects

To understand the role of event objects through a small, practical case

<ul>    <li class="even1"></li>    <li class="even2"></li>    <li class="even2"></li>    .........</ul>

UL has n sub-element Li (here only 3), if I want to respond to each Li event, then the general method is to give all Li is a separate event monitoring, so that the wording is logical, but also cumbersome

Because Li has a common parent element, and all events are consistent, here we can use a technique to deal with, and often say, "event delegation."

The event does not directly relate to the LI element, and the parent element is bound. Since the browser has this feature of event bubbling, we can bubble this event up to UL when the Li is triggered, because the UL bound event responds so it can trigger this action. The only problem is how to know which Li element is triggered?

This brings up the event object.

事件对象是用来记录一些事件发生时的相关信息的对象。事件对象只有事件发生时才会产生,并且只能是事件处理函数内部访问,在所有事件处理函数运行结束后,事件对象就被销毁

Back to the question above, since the event object is closely related to the current triggering element, we can find the Event.target from the event object from the relevant information inside.

Event.target

The target property can be an element when registering an event, or its child elements. Typically used to compare event.target and this to determine whether an event was triggered by bubbling. Handling event delegates often for event bubbling

To put it simply:Event.target represents the element that is currently triggering the event, and can be judged by a series of attributes of the current element object that is not the element we want

<div class="left">    <div class="aaron">        <ul>            <li>点击:触发一</li>            <li>点击:触发二</li>            <li>点击:触发三</li>            <li>点击:触发四</li>        </ul>    </div></div><script type="text/javascript">    //多事件绑定一    $("ul").on(‘click‘,function(e){       alert(‘触发的元素是内容是: ‘ + e.target.textContent)    })</script>
Properties and methods for jquery event objects
    • Event.type: Gets the type of event
    • Event.pagex and Event.pagey: Gets the current coordinates of the mouse relative to the page
    • Event.preventdefault () Method: block default behavior
    • Event.stoppropagation () Method: Block Event bubbling
    • Event.which: Gets which key of the mouse is clicked when the mouse is clicked
    • Event.currenttarget: The current DOM element in the event bubbling process

The DOM object of the current triggering event before bubbling, equivalent to this.

the difference between this and Event.target :

JS event is bubbling, so this is changeable, but event.target will not change, it is always directly accept the event of the target DOM element;

. This and event.target are DOM objects

If you want to use the methods in Jquey, you can convert them to jquery objects: ( t h i s ) and (event.target); For example: Use of Event.target and $ (event.target)

$("#content").click(function(event) {    $("#msg").html($("#msg").html() + "<p>外层div元素被单击</p>");    event.stopPropagation(); //阻止事件冒泡  });
Custom Event Trigger Event

Trigger used to trigger events

$(‘#elem‘).on(‘Aaron‘, function(event,arg1,arg2) {    alert("自触自定义时间") });$(‘#elem‘).trigger(‘Aaron‘,[‘参数1‘,‘参数2‘])
Triggerhandler Events

The trigger event also features a feature that bubbles on the DOM tree, so if you want to block bubbling you need to return false in the event handler or call the. Stoppropagation () method in the event object to stop the event bubbling

The trigger event is capable of triggering native and custom, but there is an unavoidable problem: Event object events cannot be implemented perfectly, after all, one is a browser, and one is its own simulation. Although. Trigger () Simulates the event object, it does not perfectly replicate events that occur naturally, to trigger event handlers that are bound by jQuery, without triggering native events, using. Triggerhandler () instead

The use of Triggerhandler and trigger is the same, focusing on the difference:

    • Triggerhandler does not trigger the default behavior of the browser, the. Triggerhandler ("submit") will not invoke the. Submit () on the form.
    • . Trigger () affects all elements that match the JQuery object, whereas. Triggerhandler () affects only the first matched element
    • Events that are triggered by using. Triggerhandler () do not bubble up in the DOM tree. If they are not triggered directly by the target element, then it will not do any processing
    • In contrast to the normal method of returning a JQuery object (so that you can use chained usage),. Triggerhandler () returns the return value of the last processed event. If no events are triggered, the undefined is returned

Example

//给input绑定一个聚焦事件$("input").on("focus",function(event,titie) {    $(this).val(‘聚焦‘)});//trigger触发focus$("button:first").click(function() {    $("input").trigger("focus",[‘触发默认事件‘]);}); //triggerHandler触发focus$("button:last").click(function() {    $("input").triggerHandler("focus",‘没有触发默认事件‘);});

The foundation of jquery--Events

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.