事件

2018-07-07  本文已影响0人  Cicada丶

一、注册事件回调方法

.click()
.focus()
.blur()
.change()
// Event setup using a convenience method
$( "p" ).click(function() {
    console.log( "You clicked a paragraph!" );
});
// Equivalent event setup using the `.on()` method
$( "p" ).on( "click", function(event) {
    console.log( "click" );
});

二、事件不会扩展到新增元素

$( document ).ready(function(){
 
    // Sets up click behavior on all button elements with the alert class
    // that exist in the DOM when the instruction was executed
    $( "button.alert" ).on( "click", function() {
        console.log( "A button with the alert class was clicked!" );
    });

    // Now create a new button element with the alert class. This button
    // was created after the click listeners were applied above, so it
    // will not have the same click behavior as its peers
    $( "<button class='alert'>Alert!</button>" ).appendTo( document.body );
});

三、事件对象

//事件发生的坐标相对于右上角(类似absolute?)
pageX, pageY
//事件的类型
type
//按下按钮还是键
which
//绑定事件时传递的数据
data
//发生事件的DOM元素
target
//事件触发时指定的命名空间
namespace
//事件发生的时间戳
timeStamp
//事件发生对象
targetObject
// Event setup using the `.on()` method with data
$( "input" ).on(
    "change",
    { foo: "bar" }, // Associate data with event binding
    function( eventObject ) {
        console.log("An input value has changed! ", eventObject.data.foo);
    }
);
//禁用默认DOM事件,比如a标签的跳转
preventDefault()
//停止传播给子元素
stopPropagation()
// Preventing a link from being followed
$( "a" ).click(function( eventObject ) {
    var elem = $( this );
    if ( elem.attr( "href" ).match( /evil/ ) ) {
        eventObject.preventDefault();
        elem.addClass( "evil" );
    }
});

$("h1").on("click",function (event) {
    console.log(event.target === this); //true
});

四、设置多个事件回调函数

// Multiple events, same handler
$( "input" ).on(
    "click change", // Bind handlers for multiple events
    function() {
        console.log( "An input was clicked or changed!" );
    }
);
// Binding multiple events with different handlers
$( "p" ).on({
    "click": function() { console.log( "clicked!" ); },
    "mouseover": function() { console.log( "hovered!" ); }
});

五、事件设置命名空间

//防止与其他的事件名称冲突,导致绑定事件覆盖其它的,设置命名空间
$( "p" ).on( "click.myNamespace", function() { /* ... */ } );
//取消注册的click.myNamespace回调事件
$( "p" ).off( "click.myNamespace" );
//取消所有.myNamespace命名空间注册的事件
$( "p" ).off( ".myNamespace" ); // Unbind all events in the namespace

六、销毁事件监听

// Tearing down all click handlers on a selection
$( "p" ).off( "click" );
// Tearing down a particular click handler, using a reference to the function
var foo = function() { console.log( "foo" ); };
var bar = function() { console.log( "bar" ); };
 
$( "p" ).on( "click", foo ).on( "click", bar );
$( "p" ).off( "click", bar ); // foo is still bound to the click event

七、设置事件只触发一次

有时,您只需要一个特定的处理程序运行一次-在此之后,您可能不希望运行任何处理程序,或者您可能希望运行另一个处理程序。.one()方法用于此目的。(比如防止重复提交)

// Switching handlers using the `.one()` method
$( "p" ).one( "click", firstClick );
 
function firstClick() {
    console.log( "You just clicked this for the first time!" );
    // Now set up the new handler for subsequent clicks;
    // omit this step if no further click responses are needed
    $( this ).click( function() { console.log( "You have clicked this before!" ); } );
}
//注意意味着只会执行最上层的那个事件一次,也就是focus事件
//不是按照注册顺序
// Using .one() to bind several events
$( "input[id]" ).one( "focus mouseover keydown", firstEvent);
 
function firstEvent( eventObject ) {
    console.log( "A " + eventObject.type + " event occurred for the first time on the input with id " + this.id );
}

八、hover()方法

// The hover helper function
$( "#menu li" ).hover(function() {
    $( this ).toggleClass( "hover" );
});
$("h1").hover(function (event) {
    console.log("in");              
    },function (event) {
    console.log("out");             
    });
});

九、DOM事件

<button onclick="alert('Hello')">Say hello</button>

js与Html分离:

// Event binding using addEventListener
var helloBtn = document.getElementById( "helloBtn" );
 
helloBtn.addEventListener( "click", function( event ) {
    alert( "Hello." );
}, false );
// Event binding using a convenience method
$( "#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" );
 
- 注意,这里就是与bind的区别,bind和on都是有事件委托机制的,不同的是on可以指定父元素监听哪些子元素
- 这里是监听所有button子元素,不指定就会监听所有子元素
- bind只有两个参数,而on多了一个过滤选择参数
$( "body" ).on( "click", "button", function( event ) {
    alert( "Hello." );
});

十、事件委托

总结

十一、事件对象

//禁用a标签跳转事件和form默认表单提交事件尤为常用
event.preventDefault();
<div style="background-color: green">
    <ul>
        <button>BUTTON</button>
        <li>A</li>
        <li>B</li>
        <li>C</li>
    </ul>
</div>

$("div:first").on("click","button",function (event) {
    alert("hello world");
})
$("button").on("click",function (event) {
    alert("我成功阻止了事件向父级传播");
    event.stopPropagation();
})

注意:JQuery封装了浏览器的event.originalEvent,当需要使用到的时候可以得到这个属性,这对于移动设备和平板电脑上的触摸事件尤其有用。

十二、事件的回调on函数

// When any <p> tag is clicked, we expect to see '<p> was clicked' in the console.
$( "p" ).on( "click", function() {
    console.log( "<p> was clicked" );
});
- 可用hover()代替
$( "div" ).on( "mouseenter mouseleave", function() {
    console.log( "mouse hovered over or left a div" );
});
$( "div" ).on({
    mouseenter: function() {
        console.log( "hovered over a div" );
    },
    mouseleave: function() {
        console.log( "mouse left a div" );
    },
    click: function() {
        console.log( "clicked on a div" );
    }
});
$( "p" ).on( "click", {
    foo: "bar"
}, function( event ) {
    console.log( "event data: " + event.data.foo + " (should be 'bar')" );
});
$( "ul" ).on( "click", "li", function() {
    console.log( "Something in a <ul> was clicked, and we detected that it was an <li> element." );
});
// Switching handlers using the `.one()` method
$( "p" ).one( "click", function() {
    console.log( "You just clicked this for the first time!" );
    $( this ).click(function() {
        console.log( "You have clicked this before!" );
    });
});
- 注意会断开所有click事件,如果需要断开某一个click事件,就需要在绑定时加上命名空间
// Unbinding all click handlers on a selection
$( "p" ).off( "click" );

十三、JQuery模拟事件触发

// This will not change the current page
$( "a" ).trigger( "click" );

十四、自定义事件

上一篇 下一篇

猜你喜欢

热点阅读