jQuery - 事件介绍

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013275171/article/details/86516773

DOM Events

监听事件的方式

糟糕的事件监听方式,以下方式使得代码难以维护。

<button onclick="alert('Hello')">Say hello</button>
<!--糟糕的事件监听方式-->

优秀的事件监听方式,使代码的维护更加方便。

<button id="helloBtn">Say hello</button>
// 使用 addEventListener 绑定事件
var helloBtn = document.getElementById( "helloBtn" );
 
helloBtn.addEventListener( "click", function( event ) {
    alert( "Hello." );
}, false ); 

// IE9 之前的浏览器,不支持使用 addEventListener 添加事件监听
// IE9 之前的浏览器,使用 attachEvent 添加事件监听
// 使用 jQuery 便捷方法,也可以化解这种情况
$( "#helloBtn" ).click(function( event ) {
    alert( "Hello." );
});
// The many ways to bind events with jQuery
// Attach an event handler directly to the button using jQuery's
// shorthand `click` method.
$( "#helloBtn" ).click(function( event ) {
    alert( "Hello." );
});
 
// Attach an event handler directly to the button using jQuery's
// `bind` method, passing it an event string of `click`
$( "#helloBtn" ).bind( "click", function( event ) {
    alert( "Hello." );
});
 
// As of jQuery 1.7, attach an event handler directly to the button
// using jQuery's `on` method.
$( "#helloBtn" ).on( "click", function( event ) {
    alert( "Hello." );
});
 
// As of jQuery 1.7, attach an event handler to the `body` element that
// is listening for clicks, and will respond whenever *any* button is
// clicked on the page.
$( "body" ).on({
    click: function( event ) {
        alert( "Hello." );
    }
}, "button" );
 
// An alternative to the previous example, using slightly different syntax.
$( "body" ).on( "click", "button", function( event ) {
    alert( "Hello." );
});

事件对象

在所有 DOM 事件回调函数中,jQuery 都会传入一个事件对象参数。

// Binding a named function
function sayHello( event ) {
    alert( "Hello." );
}
 
$( "#helloBtn" ).on( "click", sayHello );
// Preventing a default action from occurring and stopping the event bubbling
$( "form" ).on( "submit", function( event ) {
 
    // 阻止默认动作
    event.preventDefault();
 
    // 阻止事件向父元素传递,阻止事件代理动作
    event.stopPropagation();
 
    // Make an AJAX request to submit the form data
});

当同时使用 .preventDefault().stopPropagation() 方法时,可以通过 return false 来简洁的实现上述的功能。

// Logging an event's information
$( "form" ).on( "submit", function( event ) {
 
    // 阻止默认事件
    event.preventDefault();
 
    // 列印事件对象讯息
    console.log( event );
 
    // Make an AJAX request to submit the form data
});

猜你喜欢

转载自blog.csdn.net/u013275171/article/details/86516773