JQuery event model and commonly used functions

table of Contents

A binding event

Second, unbundling event

Third, the event object

Fourth, the senior event


A binding event

Use jQuery event model, you can use bind () method to create event handlers on DOM elements. Use bind function as follows:

Method Syntax: the bind
the bind (the eventType, Data, hanlder)
the bind (EventMap)

to create a function, as will focus on all of the elements in the matching of the specified event type processor
parameters
the eventType (string) as the designated processor to create name of the event type. You can use space-delimited list to specify multiple event types
by adding a dot character to separate suffix after the name of the event, these event types can be specified namespace. The remainder of this section will be described in detail
the data supplied by the caller data (object), to append to the data property of the Event instance, be used to function as a processor. If omitted, you can specify parameters for the second function processor
handler (function) that will be created as a function of the event handler. When this function is called, will pass Event instance and set the function context (this) is the bubbling phase of the current element
eventMap (objects) a JavaScript object that allows you to create multiple event types of processors in a single call. The name attribute specifies the event type (same eventType parameter), the value of the attribute providing a processor
return value
package set

  • for example
/*
为页面上的每个图片绑定提供内联函数,作为单击事件处理器
*/
$('img').bind('click',function(event){alert('Hi there!');});

/*
对img图片添加3个事件
*/
$('img').bind({
  click: function(event) { /* handle clicks */ },
  mouseenter: function(event) { /* handle mouseenters */ },
  mouseleave: function(event) { /* handle mouseleaves */ }
});

To allow developers to more easily binding event, JQuery encapsulates common events in order to save more code. We call it the short event, see the following table.

Shorthand event binding method
Method name Triggering conditions description
click(fn) mouse Each trigger a matching element click (click) event
dblclick(fn) mouse Each dblclick trigger matching element (double-click) event
mousedown(fn) mouse Each trigger a mousedown (click) event of matching elements
mouseup(fn) mouse Each trigger a matching element mouseup (click pop-up) events
mouseover(fn) mouse Each trigger a mouseover matching elements (mouse moved) events
mouseout(fn) mouse Each trigger a matching element mouseout (mouse out) events
mousemove(fn) mouse Each mousemove trigger a matching element (mouse movement) events
mouseenter(fn) mouse Each trigger a matching element mouseenter (mouse through) incidents
mouseleave(fn) mouse mouseleave trigger each matched element (mouse piercing) events
keydown(fn) keyboard Each trigger a matching element keydown (keyboard press) events
keyup(fn) keyboard Each trigger a matching element keyup (press keyboard pops up) event
keypress(fn) keyboard Trigger the matching element of keypress (keyboard press) events
unload(fn) File Bind a function to be performed when uninstalling this page
resize(fn) File Each trigger a matching element resize (change the size of the document) event
scroll(fn) File Each trigger a matching element scroll (scrollbar) events
focus(fn) Forms Trigger the matching element of focus (the focus of activation) event
Blur (Fan) Forms Each trigger a matching element blur (focus loss) events
focusin(fn) Forms Each trigger a matching element focusin (focus activation) event
focusout(fn) Forms Each trigger a matching element focusout (focus loss) events
select(fn) Forms Each trigger a matching element select (the selected text) events
change(fn) Forms Trigger the matching element of change (value change) events
submit(fn) Forms submit to trigger each matched element (form submission) event
  • for example

Most methods of encapsulation here are better understood, we do not need eleven presentations confirmed, the focus needs to pay attention to look at a few shorthand method of distinguishing.
.mouseover () and .mouseout () represents the mouse moved in and out when triggered. JQuery then further encapsulates another group: .mouseenter () and .mouseleave () indicates mouse piercing through the trigger time. So what are the differences on the nature of these two groups? Instructions on the manual is: .mouseenter () and .mouseleave () which passes through the sub-group elements will not trigger, but .mouseover () and .mouseout () is triggered.

<!--HTML页面设置-->
    <div style="width:200px;height:200px;background:green;">
      <p style="width:100px;height:100px;background:red;">
    </div>
    <strong></strong>
<script>
    //mouseover移入
    $('div').mouseover(function () {//移入div 会触发,移入p 再触发
      $('strong').html(function (index, value) {
        return value+'1';
      });
    });
    //mouseenter穿过
    $('div').mouseenter(function () {//穿过div 或者p
      $('strong').html(function (index, value) {//在这个区域只触发一次
        return value+'1';
      });
    });
    //mouseout移出
    $('div').mouseout(function () { //移出p 会触发,移出div 再触发
      $('strong').html(function (index, value) {
        return value+'1';
      });
    });
    //mouseleave穿出
    $('div').mouseleave(function () {//移出整个div 区域触发一次
      $('strong').html(function (index, value) {
        return value+'1';
      });
    });
    .keydown()、.keyup()返回的是键码,而.keypress()返回的是字符编码。
    $('input').keydown(function (e) {
      alert(e.keyCode);//按下a 返回65
    });
    $('input').keypress(function (e) {
      alert(e.charCode);//按下a 返回97
    });
</script>

Note: e.keyCode and e.charCode will produce different results in both events swaps, in addition to character as well as some non-character keys difference.

.focus () and .blur () denote the cursor activation and loss, event-triggered timing is the current element. The .focusin () and .focusout () also indicates that the cursor is activated and lost, but the timing of the trigger event may be child elements.

<!--HTML部分-->
<div style="width:200px;height:200px;background:red;">
    <input type="text" value="" />
</div>
<strong></strong>

<script>
    //focus光标激活
    $('input').focus(function () {//当前元素触发
      $('strong').html('123');
    });
    //focusin光标激活
    $('div').focusin(function () {//绑定的是div 元素,子类input 触发
      $('strong').html('123');
    });
</script>

Note: .blur () and .focusout () indicates that the cursor is lost, and the activation is similar to the current element must be a trigger, and the other child element can be triggered.

JQuery offers many of the most popular events effect, the combination of a number of functions to achieve a number of complex events, such as switching, intelligent load and so on.

Composite event
Method name description
ready(fn) When the DOM is loaded trigger event
hover([fn1,]fn2) When the mouse is moved trigger first fn1, out of the trigger fn2
toggle(fn1,fn2[,fn3..])   Obsolete, when mouse click trigger fn1, and then click the trigger fn2. ..
  • for example
//背景移入移出切换效果
    $('div').hover(function () {
      $(this).css('background', 'black');//mouseenter 效果
    }, function () {
      $(this).css('background', 'red');//mouseleave 效果,可省略
    });

Note: .hover () method is a combination of .mouseenter () method and .mouseleva () method, not .mouseover () and .mouseout () method.

.toggle () This method is rather special, this method has two meanings: the first layer of meaning that have been spent with version 1.8, version 1.9 delete usage of the click switch usage composite event; a second layer comprising I will in the animation to explain that chapter. Since discarded, and should not be used. The reason being deleted are: to reduce clutter and enhance the potential of modularity. But you really want to use this method, and do not want to write a similar function yourself, you can download jquery-migrate.js file, be backward-compatible method has been removed.

//背景点击切换效果(1.9 版删除了)
    <script type="text/javascript" src="jquery-migrate-1.2.1.js"></script>
    $('div').toggle(function () {//第一次点击切换
      $(this).css('background', 'black');
    }, function () {//第二次点击切换
      $(this).css('background', 'blue');
    }, function () {//第三次点击切换
      $(this).css('background', 'red');
    });
/*
注意:由于官方已经删除掉这个方法,所以也是不推荐使用的,
如果在不基于向下兼容的插件JS。我们可以自己实现这个功能。
*/

    var flag = 1;//计数器
    $('div').click(function () {
      if (flag == 1) {//第一次点击
        $(this).css('background', 'black');
        flag = 2;
      } else if (flag == 2) {//第二次点击
        $(this).css('background', 'blue');
        flag = 3
      } else if (flag == 3) {//第三次点击
        $(this).css('background', 'red');
        flag = 1
      }
    });

Second, unbundling event

jQuery provides additional functionality for event processing, is to group event handler by specifying namespace. And conventional different namespaces (specified by the namespace prefix), by adding to it the name of the event separated by dots suffix to specify the namespace. In fact, if you prefer, you can use multiple suffixes Events into multiple namespaces.

Binding events grouped in this way, then they can be considered as a unit for its operation.

For example, a page has two modes: display mode and edit mode. In edit mode, the event listener is placed on many elements of the page, but in the display mode These listeners do not apply, so when the page to leave edit mode, you need to remove these listeners. We can specify the namespace for the event in edit mode, the code is as follows:

$('#thing1').bind('click.editMode',someListener);
$('#thing2').bind('click.editMode',someOtherListener);

//当页面离开编辑模式需要删除所有的绑定时
$('*').unbind('click.editMode');

Methods Syntax: unbind
unbind (eventType, listener)
unbind (Event)

is set to delete all the elements of the packaging specified by the optional parameter passed event handler. If no parameters, it will remove all the listeners from the element
parameters
eventType (string) If provided, only remove listeners created for the specified event type
listener (function) If provided, identify the specified listener to be deleted an
event (events) delete triggers event listener example described
the return value of
the package set

Third, the event object

The event object is an object event, by accepting the default handler passes. E before event handler is an event object, event object has many attributes and methods available, the following examples:

//通过处理函数传递事件对象
    $('input').bind('click', function (e) { //接受事件对象参数
      alert(e);
    });
event object properties
Property name description
type Gets the event type of event, such as click
target Gets the DOM element binding events
data Additional data acquisition event call
relatedTarget Get moved in and out of the target point to leave or enter the DOM element
currentTarget Get triggered before bubbling DOM element, this is equivalent to
pageX, pagey Relative to the page origin obtain horizontal / vertical
screenX,screenY Acquiring a display screen position of the horizontal / vertical (non JQuery Package)
clientX, clientY Get a page with respect to the viewport horizontal / vertical (non JQuery Package)
result Recent non-undefined value returned from the previous event handler
timeStamp Acquires a time stamp event triggered
which For keyboard events, key events specified trigger digital code; for mouse events, which specifies the press of a button (1 button, 2 button, 3 right). Which property should be used instead of the button attribute, because it can not guarantee the consistency cross-browser button property
altKey When a trigger event, if the Alt key has been pressed, it is set to true, otherwise false. In most Mac keyboard Alt key labeled Option
ctrlKey When a trigger event, if Ctrl key has been pressed, it is set to true, false otherwise
metaKey When a trigger event, if the Meta key has been pressed, it is set to true, otherwise false. On the PC Meta key is Ctrl key, and the Command key on a Mac
shiftKey When a trigger event, if the Shift key has been pressed, it is set to true, false otherwise
  • for example
//通过event.type 属性获取触发事件名
$('input').click(function (e) {
    alert(e.type);
});
//通过event.target 获取绑定的DOM 元素
$('input').click(function (e) {
    alert(e.target);
});
//通过event.data 获取额外数据,可以是数字、字符串、数组、对象
$('input').bind('click', 123, function () {//传递data 数据
    alert(e.data);//获取数字数据
);

Note: If the string to pass: '123', if the array is passed to: [123, 'ABC'], if the object is to transfer:

{user: 'Lee', age: 100}。数组的调用方式是:e.data[1],对象的调用方式是:e.data.user。
    //event.data获取额外数据,对于封装的简写事件也可以使用
    $('input').click({user: 'Lee', age: 100},function (e) {
    alert(e.data.user);
    });

Note: The key value pairs can be in quotes, may not be added; at the time of the call can also use an array of ways:

    alert(e.data['user']);
    //获取移入到div 之前的那个DOM 元素
    $('div').mouseover(function (e) {
         alert(e.relatedTarget);
    });

    //获取移出div 之后到达最近的那个DOM 元素
    $('div').mouseout(function (e) {
        alert(e.relatedTarget);
    });

    //获取绑定的那个DOM 元素,相当于this,区别于event.target
    $('div').click(function (e) {
         alert(e.currentTarget);
    });

注意:event.target得到的是触发元素的DOM,event.currentTarget得到的是监听元素的DOM。而this也是得到监听元素的DOM。

    //获取上一次事件的返回值
    $('div').click(function (e) {
    return '123';
    });

    $('div').click(function (e) {
    alert(e.result);
    });

    //获取当前的时间戳
    $('div').click(function (e) {
    alert(e.timeStamp);
    });

    //获取鼠标的左中右键
    $('div').mousedown(function (e) {
    alert(e.which);
    });

    //获取键盘的按键
    $('input').keyup(function (e) {
    alert(e.which);
    });

    //获取是否按下了ctrl 键,meta 键不存在,导致无法使用
    $('input').click(function (e) {
    alert(e.ctrlKey);
    });

    //获取触发元素鼠标当前的位置
    $(document).click(function (e) {
    alert(e.screenY+ ',' + e.pageY + ',' + e.clientY);
    });
event对象方法
方法 描述
preventDefault() 阻止任意默认的语义动作(比如表单提交、链接重定向、复选框状态的改变等)发生
stopPropagation() 停止事件沿着DOM树向上进一步传播。当前目标元素上附加的事件不受影响。不仅支持浏览器定义的事件,而且支持自定义事件
stopImmediatePropagation() 停止所有事件的进一步传播,包括附加在当前目标元素上的事件
isDefaultPrevented() 如果已经在此实例上调用了preventDefault() 方法,则返回true
isPropagationStopped() 如果已经在此实例上调用了stopPropagation() 方法,则返回true
isImmediatePropagationStopped() 如果已经在此实例上调用了stopImmediatePropagation() 方法,则返回true

四、高级事件

在事件触发的时候,有时我们需要一些模拟用户行为的操作。例如,当网页加载完毕后自行点击一个按钮触发一个事件,而不是由用户去点击。

    //点击按钮事件
    $('input').click(function () {
      alert('我的第一次点击来自模拟!');
    });
    //模拟用户点击行为
    $('input').trigger('click');
    //可以合并两个方法
    $('input').click(function () {
      alert('我的第一次点击来自模拟!');
    }).trigger('click');

有时在模拟用户行为的时候,我们需要给事件执行传递参数,这个参数类似于event.data的额外数据,可以是数字、字符串、数组、对象。

$('input').click(function (e, data1, data2) {
      alert(data1 + ',' + data2);
    }).trigger('click', ['abc', '123']);

注意:当传递一个值的时候,直接传递即可。当两个值以上时,需要在前后用中括号包含起来。但不能认为是数组形式,下面给出一个复杂的说明。

$('input').click(function (e, data1, data2) {
      alert(data1.a + ',' + data2[1]);
    }).trigger('click', [{'a': '1', 'b': '2'}, ['123','456']]);

除了通过JavaScript事件名触发,也可以通过自定义的事件触发。所谓自定义事件,其实就是一个被.bind()绑定的任意函数。

$('input').bind('myEvent', function () {
      alert('自定义事件!');
    }).trigger('myEvent');

.trigger()方法提供了简写方案,只要想让某个事件执行模拟用户行为,直接再调用一个空的同名事件即可。

$('input').click(function () {
      alert('我的第一次点击来自模拟!');
    }).click();//空的click()执行的是trigger()

这种便捷的方法,JQuery几乎所有常用的事件都提供了。

JQuery常用事件
blur focusin mousedown resize
change focusout mousenter scroll
click keydown mouseleave select
dblclick keypress mousemove submit
error keyup mouseout unload
focus load mouseover  

JQuery还提供了另外一个模拟用户行为的方法:.triggerHandler();这个方法的使用和.trigger()方法一样。

$('input').click(function () {
      alert('我的第一次点击来自模拟!');
    }).triggerHandler('click');

在常规的使用情况下,两者几乎没有区别,都是模拟用户行为,也可以传递额外参数。但在某些特殊情况下,就产生了差异:
(1)triggerHandler()方法并不会触发事件的默认行为,而.trigger()会。

$('form').trigger('submit');//模拟用户执行提交,并跳转到执行页面
$('form').triggerHandler('submit');//模拟用户执行提交,并阻止的默认行为

// 如果我们希望使用.trigger()来模拟用户提交,并且阻止事件的默认行为,则需要这么写:
$('form').submit(function (e) {
    e.preventDefault();//阻止默认行为
}).trigger('submit');

(2)triggerHandler()方法只会影响第一个匹配到的元素,而.trigger()会影响所有。
(3)triggerHandler()方法会返回当前事件执行的返回值,如果没有返回值,则返回undefined;而.trigger()则返回当前包含事件触发元素的JQuery对象(方便链式连缀调用)。

alert($('input').click(function () {
      return 123;        
    }).triggerHandler('click'));//返回123,没有return 返回

(4)trigger()在创建事件的时候,会冒泡。但这种冒泡是自定义事件才能体现出来,是JQuery扩展于DOM的机制,并非DOM特性。而.triggerHandler()不会冒泡。


jQuery提供了我们所期望的live() 方法,该方法允许预先为那些还不存在的元素创建事件处理器。live() 的语法如下。

方法语法:live
live(eventType, data, listener)

当指定类型的事件在元素(任何用来创建包装集的与选择器相匹配的元素)上发生时,会将传入的监听器作为处理器调用,而无论在调用live 方法时这些元素是否已经存在
参数
eventType (字符串)指定处理器将要调用的事件类型的名称。和bind() 不同,不能指定空格分隔的事件类型列表3
3 这个说法不对,从jQuery1.4开始已经可以为live() 方法的第一个参数指定空格分隔的事件类型列表或者自定义事件类型了。
data (对象)调用者提供的数据,用来附加到Event 实例的data 属性,以便为处理器函数所使用。如果省略,可以指定第二个参数为处理器函数
listener (函数)将要作为事件处理器被调用的函数。当调用此函数时,会向此函数传入Event实例,并设置目标元素为函数上下文(this )
返回值
包装集

如果这个方法的语法让你想起bind() 方法的语法,那就对了。这个方法的定义和行为与bind() 很相似。不同之处是,当相应的事件发生时,该方法会为所有匹配选择器的元素触发此事件,甚至包括那些在调用live() 的时候还不存在的元素。

$('div.attendToMe').live(
  'click',
   function(event){ alert(this); }
);

        在页面的整个生命周期内,单击任意拥有类attendToMe 的<div> 元素都会调用事件处理器并传入一个事件实例。而且前面的代码不需要放置于就绪处理器中,因为“live”事件不关心DOM是否已经存在。
        利用live() 方法,可以非常容易地在页面上的某个地方创建需要的事件处理器,而无需担心元素是否已经存在,或者什么时候创建元素。
        但是使用live() 时必须要遵守一些注意事项。因为它和bind() 很相似,你可能会期望“live”事件完全按照与原生事件相同的方式工作,但是它们是有差异的,在某些页面中这种差异可能很重要,也可能无关紧要。
        首先,要意识到“live”事件不是 原生的“普通”事件。当类似于单击的事件发生时,它会沿着DOM元素向上传播(如前所述),并调用每一个已经创建的事件处理器。一旦事件到达用来创建包装集的上下文,也就是调用live() 的地方(通常是文档根节点4 ),上下文会在子节点中检查匹配“live”选择器的元素5 。“live”事件处理器会在每个匹配的元素上触发,并且这个已触发的事件不能 继续传播。

方法语法:die
die(eventType, listener)

删除由live() 创建的“live”事件处理器,并且阻止在将来创建的元素上调用处理器,这些元素是与调用live() 时使用的选择器相匹配的元素
参数
eventType (字符串)如果提供,则只删除为指定事件类型创建的监听器
listener (函数)如果提供,则找出将要删除的指定监听器
返回值
包装集

发布了46 篇原创文章 · 获赞 48 · 访问量 3万+

Guess you like

Origin blog.csdn.net/qq_39559641/article/details/104049637