温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

jQuery中的事件实例分析

发布时间:2022-05-16 14:25:37 来源:亿速云 阅读:156 作者:iii 栏目:开发技术

这篇“jQuery中的事件实例分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“jQuery中的事件实例分析”文章吧。

一、概述:

当用户与浏览器进行交互时这些方法被用于注册行为生效,并进一步处理这些注册行为。

二、绑定事件处理器

1、.on():

在选定的元素上绑定一个或多个事件处理函数。

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

Example1: 当点击段落时,显示该段落中的文本:

$("p").on("click", function(){
  alert( $(this).text() );
});

Example2: 向事件处理函数中传入数据,并且在事件处理函数中通过名字来获取传入的数据:

function myHandler(event) {
  alert(event.data.foo);
}
$("p").on("click", {foo: "bar"}, myHandler)

Example3: 取消表单的提交动作,并且通过返回 false 的方法来防止事件冒泡:

$("form").on("submit", false)

Example4: 通过使用 .preventDefault(),仅取消默认的动作。

$("form").on("submit", function(event) {
  event.preventDefault();
});

Example5: 通过使用 .stopPropagation(),防止提交事件的冒泡行为,但是并不禁止提交行为。

$("form").on("submit", function(event) {
  event.stopPropagation();
});

Example6: 添加并触发自定义事件(非浏览器事件)。

$("p").on("myCustomEvent",function(event,myName){
 $(this).text(myName+",hithere!");
 $("span")
  .stop()
  .css("opacity",1)
  .text("myName="+myName)
  .fadeIn(30)
  .fadeOut(1000);
});
$("button").click(function(){
 $("p").trigger("myCustomEvent",["John"]);
});

Example7: 使用 对象 同时添加多个事件处

$("div.test").on({
  click: function(){
    $(this).toggleClass("active");
  },
  mouseenter: function(){
    $(this).addClass("inside");
  },
  mouseleave: function(){
    $(this).removeClass("inside");
  }
});

2、.one():

为元素的事件添加处理函数。处理函数在每个元素上每种事件类型最多执行一次。

  • .one( events [, data ], handler(eventObject) )

  • .one( events [, selector ] [, data ], handler(eventObject) )

Example1: 为每个 div 绑定一次性 click 事件。

var n = 0;
$( "div" ).one( "click", function() {
  var index = $( "div" ).index( this );
  $( this ).css({
    borderStyle: "inset",
    cursor: "auto"
  });
  $( "p" ).text( "Div at index #" + index + " clicked." +
    " That's " + (++n) + " total clicks." );
});

Example2: 在每个段落上第一次点击时,显示该段落的内容:

$( "p" ).one( "click", function() {
  alert( $( this ).text() );
});

Example3: 处理函数在每个元素上每种事件类型只执行一次。

var n = 0;
$(".target").one("click mouseenter", function() {
  $(".count").html(++n);
});

3、.off():

移除一个事件处理函数。

.off( events [, selector ] [, handler(eventObject) ] )

Example1: 为有颜色的按钮添加并移除事件处理。

function flash() {
  $( "div" ).show().fadeOut( "slow" );
}

$( "#bind" ).click(function() {
  $( "body" )
    .on( "click", "#theone", flash )
    .find( "#theone" )
      .text( "Can Click!" );
});

$( "#unbind" ).click(function() {
  $( "body" )
    .off( "click", "#theone", flash )
    .find( "#theone" )
      .text( "Does nothing..." );
});

Example2: 移除所有段落上的事件:

$( "p" ).off();

Example3: 移除所有段落上的代理事件:

$( "p" ).off( "click", "**" );

Example4: 通过传入的第三个参数,仅移除先前绑定的事件处理函数:

var foo = function() {
  // Code to handle some kind of event
};
 
// ... Now foo will be called when paragraphs are clicked ...
$( "body" ).on( "click", "p", foo );
 
// ... Foo will no longer be called.
$( "body" ).off( "click", "p", foo );

Example5: 通过指定名字空间,解除绑定表单上所有的代理事件:

var validate = function() {
  // Code to validate form entries
};
 
// Delegate events under the ".validator" namespace
$( "form" ).on( "click.validator", "button", validate );
 
$( "form" ).on( "keypress.validator", "input[type='text']", validate );
 
// Remove event handlers in the ".validator" namespace
$( "form" ).off( ".validator" );

4、.trigger():

触发被选元素的指定事件类型。

.trigger( eventType [, extraParameters ] ) 
Example1: 点击 button #2 时,同时触发 button #1 的点击事件。

$( "button" ).first().click(function() {
  update( $( "span" ).first() );
});
 
$( "button" ).last().click(function() {
  $( "button" ).first().trigger( "click" );
  update( $( "span" ).last() );
});
 
function update( j ) {
  var n = parseInt( j.text(), 10 );
  j.text( n + 1 );
}

Example2: 若要提交第一个表单但又不想使用 submit() 函数,请尝试如下方法:

$("form:first").trigger("submit")

Example3: 若要提交第一个表单但又不想使用 submit() 函数,请尝试如下方法:

var event = jQuery.Event( "submit" );
$( "form" ).first().trigger( event );
if ( event.isDefaultPrevented() ) {
  // Perform an action...
}

Example4: 向事件中传入任意的数据:

$( "p" )
  .click(function( event, a, b ) {
    // When a normal click fires, a and b are undefined
    // for a trigger like below a refers to "foo" and b refers to "bar"
  })
  .trigger( "click", [ "foo", "bar" ] );

Example5: 通过 event 对象,向事件中传入任意的数据:

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

Example6: 另外一种通过 event 对象传入数据的方法:

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

5、.triggerHandler():

一个事件执行附加到元素的所有处理程序。

.triggerHandler( eventType [, extraParameters ] )

如果您使用 .triggerHandler() 触发 focus 事件,那么它只会触发绑定了该事件的处理函数,而浏览器的默认 focus 动作是不会被触发的。

$( "#old" ).click(function() {
  $( "input" ).trigger( "focus" );
});
$( "#new" ).click(function() {
  $( "input" ).triggerHandler( "focus" );
});
$( "input" ).focus(function() {
  $( "Focused!" ).appendTo( "body" ).fadeOut( 1000 );
});

6、jQuery.proxy():

接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文语境。

  • jQuery.proxy( function, context [, additionalArguments ] )

  • jQuery.proxy( context, name [, additionalArguments ] )

Example1: 修改使用参数为"function, context"的jQuery.proxy()方法绑定的点击事件的上下文语境。并且在第一次点击事件执行后,解除原先的绑定。

var me = {
  type: "zombie",
  test: function( event ) {
    // Without proxy, `this` would refer to the event target
    // use event.target to reference that element.
    var element = event.target;
    $( element ).css( "background-color", "red" );
 
    // With proxy, `this` refers to the me object encapsulating
    // this function.
    $( "#log" ).append( "Hello " + this.type + "
" );
    $( "#test" ).off( "click", this.test );
  }
};
 
var you = {
  type: "person",
  test: function( event ) {
    $( "#log" ).append( this.type + " " );
  }
};
 
// Execute you.test() in the context of the `you` object
// no matter where it is called
// i.e. the `this` keyword will refer to `you`
var youClick = $.proxy( you.test, you );
 
// attach click handlers to #test
$( "#test" )
  // this === "zombie"; handler unbound after first click
  .on( "click", $.proxy( me.test, me ) )
 
  // this === "person"
  .on( "click", youClick )
 
  // this === "zombie"
  .on( "click", $.proxy( you.test, me ) )
 
  // this === "element"
  .on( "click", you.test );

Example2: 通过调用参数为"context, function name"的jQuery.proxy()方法,强制修改函数的上下文语境。 并且在第一次点击事件执行后,解除绑定。

var obj = {
  name: "John",
  test: function() {
    $( "#log" ).append( this.name );
    $( "#test" ).off( "click", obj.test );
  }
};
$( "#test" ).on( "click", jQuery.proxy( obj, "test" ) );

Example3: 更改绑定点击处理程序函数的上下文。

var me = {
  // I'm a dog
  type: "dog",
  // Note that event comes *after* one and two
  test: function( one, two, event ) {
    $( "#log" )
       // `one` maps to `you`, the 1st additional
      // argument in the $.proxy function call
      .append( "Hello " + one.type + ":")// The `this` keyword refers to `me`
      // (the 2nd, context, argument of $.proxy)
      .append( "I am a " + this.type + ", " )
 
      // `two` maps to `they`, the 2nd additional
      // argument in the $.proxy function call
      .append( "and they are " + two.type + "." )
 
      // The event type is "click"
      .append( "Thanks for " + event.type + "ing." )
 
      // The clicked element is `event.target`,
      // and its type is "button"
      .append( "the " + event.target.type + "." );
  }
};
 
var you = { type: "cat" };
var they = { type: "fish" };
 
// Set up handler to execute me.test() in the context
// of `me`, with `you` and `they` as additional arguments
var proxy = $.proxy( me.test, me, you, they );
 
$( "#test" )
  .on( "click", proxy );

三、浏览器事件

1、.resize():

为 JavaScript 的 "resize" 事件绑定一个处理函数,或者触发元素上的该事件。

.resize( [eventData ], handler(eventObject) )

当窗口大小改变时(或改变后),查看窗口的宽度:

$(window).resize(function() {
  $('body').prepend('' + $(window).width() + '');
});

2、.scroll():

为 JavaScript 的 "scroll" 事件绑定一个处理函数,或者触发元素上的该事件。

.scroll( [eventData ], handler(eventObject) )

在页面滚动时触发一系列动作:

$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$(window).scroll(function () {
  $("span").css("display", "inline").fadeOut("slow");
});

四、文档加载

1 .ready(handler)

返回: jQuery:当DOM准备就绪时,指定一个函数来执行。

可以在同一个页面中无限次地使用$(document).ready()事件。其中注册的函数会按照(代码中的)先后顺序依次执行。

显示当DOM加载的信息。

ready() 方法通常用于一个匿名函数:

$( document ).ready(function() {
  // Handler for .ready() called.
});

代码:

$(function() {
    $("p" ).text( "The DOM is now loaded and can be manipulated." );
});

2、$.holdReady():

暂停或恢复.ready() 事件的执行。

延迟就绪事件,直到已加载的插件。

$.holdReady( true );
$.getScript( "myplugin.js", function() {
  $.holdReady( false );
});

3、$.ready:

一个类似于promise的对象(或“thenable”),它在文档准备好时解析。

ready(), 它就是使用了这个对象。

Example1:使用jQuery.when监听准备好的文档。

$.when( $.ready ).then(function() {
  // Document is ready.
});

Example2:典型的用法涉及到另一个promise,使用jQuery.when。

$.when(
  $.getJSON( "ajax/test.json" ),
  $.ready
).done(function( data ) {
  // Document is ready.
  // Value of test.json is passed as `data`.
});

五、表单事件

1、.blur():

为 "blur" 事件绑定一个处理函数,或者触发元素上的 "blur" 事件(注:此事件不支持冒泡)。

2、.change( [eventData ], handler )

为JavaScript 的 "change" 事件绑定一个处理函数,或者触发元素上的 "change" 事件。

Example1: 为 select 元素添加 change 事件,将选中的项目显示在 div 中。

$("select").change(function () {
  var str = "";
  $("select option:selected").each(function () {
            str += $(this).text() + " ";
  });
  $("div").text(str);
})
.change();

Example2: 所有文本输入元素添加一个的有效性测试:

$("input[type='text']").change( function() {
  // check input ($(this).val()) for validity here
});

3、其他表单事件

  • .focus():为 JavaScript 的 "focus" 事件绑定一个处理函数,或者触发元素上的 "focus" 事件。

  • .focusin():将一个事件函数绑定到"focusin" 事件。

  • .focusout():将一个事件函数绑定到"focusout" 事件。

  • .select():为 JavaScript 的 "select" 事件绑定一个处理函数,或者触发元素上的该事件。

  • .submit():为 JavaScript 的 "submit" 事件绑定一个处理函数,或者触发元素上的该事件。 
    .submit( [eventData ], handler(eventObject) )

Example1: 如果你想根据一个标识来阻止表单被提交的话,可以像下面这样做:

$("form").submit(function() {
  if ($("input:first").val() == "correct") {
    $("span").text("Validated...").show();
    return true;
  }
  $("span").text("Not valid!").show().fadeOut(1000);
  return false;
});

Example2: 如果你想根据一个标识来阻止表单被提交的话,可以像下面这样做:

$("form").submit( function () {
  return this.some_flag_variable;
} );

Example3: 触发页面上第一个表单的提交事件:

$("form:first").submit();

六、键盘事件

  • .keydown():为 "keydown" 事件绑定一个处理函数,或者触发元素上的 "keydown" 事件。

  • .keypress():为 "keypress" 事件绑定一个处理函数,或者触发元素上的 "keypress" 事件。

  • .keyup():为 "keyup" 事件绑定一个处理函数,或者触发元素上的 "keyup" 事件。 
    .keyup( [eventData ], handler(eventObject) )

当在文本框中松开一个按键时,显示 keyup 事件的 event 对象。(使用一个简单的 $.print 插件)。

var xTriggered = 0;
$('#target').keyup(function(event) {
   xTriggered++;
   var msg = 'Handler for .keyup() called ' + xTriggered + ' time(s).';
  $.print(msg, 'html');
  $.print(event);
}).keydown(function(event) {
  if (event.which == 13) {
    event.preventDefault();
  }
});
 
$('#other').click(function() {
  $('#target').keyup();
});

七、鼠标事件

1、.click():

为 JavaScript 的"click" 事件绑定一个处理器,或者触发元素上的 "click" 事件。

.click( [eventData ], handler(eventObject) )

Example1: 点击段落时隐藏他们:

$("p").click(function () {
    $(this).slideUp();
});

Example2: 在页面上所有段落上触发click事件。

$("p").click();

2、其他鼠标事件

  • .contextmenu():为 JavaScript 的"contextmenu" 事件绑定一个处理器,或者触发元素上的 "contextmenu" 事件。

  • .dblclick():为JavaScript 的 "dblclick" 事件绑定一个处理函数,或者触发元素上的 "dblclick" 事件。

  • .hover():将二个事件函数绑定到匹配元素上,分别当鼠标指针进入和离开元素时被执行。将一个单独事件函数绑定到匹配元素上,分别当鼠标指针进入和离开元素时被执行。

  • .mousedown():为 JavaScript 的 "mousedown" 事件绑定一个处理函数,或者触发元素上的该事件。

  • .mouseenter():为 mouse enters(鼠标进入) 事件绑定一个处理函数,或者触发元素上的 mouse enters(鼠标进入) 事件。

  • .mouseleave():为 mouse leaves(鼠标离开) 事件绑定一个处理函数,或者触发元素上的 mouse leaves(鼠标离开) 事件。

  • .mousemove():为 JavaScript 的 "mousemove" 事件绑定一个处理函数,或者触发元素上的该事件。

  • .mouseout():为 JavaScript 的 "mouseout" 事件绑定一个处理函数,或者触发元素上的该事件。(注:支持事件冒泡)

  • .mouseover():为 JavaScript 的 "mouseover" 事件绑定一个处理函数,或者触发元素上的该事件。(注:支持事件冒泡)

  • .mouseup():为 JavaScript 的 "mouseup" 事件绑定一个处理函数,或者触发元素上的该事件。

八、事件对象

1、属性列表:

  • metaKey:表示事件触发时哪个Meta键被按下。

  • pageX、pageY:鼠标相对于文档的左边缘、顶部边缘的位置(坐标)。

  • relatedTarget:在事件中涉及的其它任何DOM元素。

  • target:触发事件的DOM元素。

  • which:针对键盘和鼠标事件,这个属性能确定你到底按的是哪个键。

  • type:描述事件的性质。

  • currentTarget:在事件冒泡过程中的当前DOM元素。

  • data:当当前正在执行的处理程序绑定时,一个可选的数据对象传递给一个事件方法。

  • delegateTarget:绑定了当前正在调用jQuery 事件处理器的元素。

  • namespace:当事件被触发时此属性包含指定的命名空间。

  • result:事件被触发的一个事件处理程序的最后返回值,除非值是 undefined。

  • timeStamp:这个属性返回事件触发时距离1970年1月1日的毫秒数。

某些事件可能有它们特定的属性。 那些属性可以存取在event.originalEvent对象上。

// add the dataTransfer property for use with the native `drop` event
// to capture information about files dropped into the browser window
jQuery.event.props.push( "dataTransfer" );

2、函数列表:

  • event.isDefaultPrevented():根据事件对象中是否调用过 event.preventDefault() 方法,来返回一个布尔值。

  • event.isImmediatePropagationStopped():根据事件对象中是否调用过 event.stopImmediatePropagation() 方法,来返回一个布尔值。

  • event.isPropagationStopped():根据事件对象中是否调用过 event.stopPropagation() 方法,来返回一个布尔值。

  • event.preventDefault():如果调用这个方法,默认事件行为将不再触发。

  • event.stopImmediatePropagation():阻止剩余的事件处理函数执行并且防止事件冒泡到DOM树上。

  • event.stopPropagation():防止事件冒泡到DOM树上,也就是不触发的任何前辈元素上的事件处理函数。

记录按键:

$('#whichkey').bind('keydown',function(e){
  $('#log').html(e.type + ': ' +  e.which );
});

以上就是关于“jQuery中的事件实例分析”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI