事件
2018-07-07 本文已影响0人
Cicada丶
一、注册事件回调方法
.click()
.focus()
.blur()
.change()
// Event setup using a convenience method
$( "p" ).click(function() {
console.log( "You clicked a paragraph!" );
});
- 都可以用on代替
// 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 );
});
三、事件对象
- 可以设置一个event参数,在事件发生时会传递给回调函数
- 最常用的用法是event.preventDefault()禁用掉默认DOM事件
- event也包含事件的很多信息数据
//事件发生的坐标相对于右上角(类似absolute?)
pageX, pageY
//事件的类型
type
//按下按钮还是键
which
//绑定事件时传递的数据
data
//发生事件的DOM元素
target
//事件触发时指定的命名空间
namespace
//事件发生的时间戳
timeStamp
//事件发生对象
targetObject
- 绑定data
// 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()
- 转换为Jquery对象
// 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!" ); } );
}
- .one()还可以用于绑定多个事件
//注意意味着只会执行最上层的那个事件一次,也就是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()方法
- 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>
- 首先,我们将视图代码(HTML)与交互代码(JS)耦合起来。这意味着,每当我们需要更新功能时,我们都必须编辑HTML,这只是一个糟糕的实践和维护的噩梦。
- 第二,它是不可伸缩的。如果您必须将此功能附加到多个按钮上,那么您不仅会用一堆重复的代码在页面上膨胀,而且还会再次破坏可维护性。
js与Html分离:
// Event binding using addEventListener
var helloBtn = document.getElementById( "helloBtn" );
helloBtn.addEventListener( "click", function( event ) {
alert( "Hello." );
}, false );
- Jquery的方式
// 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." );
});
- 从jQuery 1.7开始,所有事件都通过on方法,无论是直接调用它,还是使用别名/快捷方法(如bind或click,则映射到on方法内部。考虑到这一点,使用on方法,因为其他的都只是语法糖,并且使用on方法将产生更快和更一致的代码。
十、事件委托
- 事件委托就是利用事件冒泡原理实现的!
- 事件冒泡:就是事件从最深节点开始,然后逐步向上传播事件;
- 例:页面上有一个节点树,div > ul > li > a比如给最里面的a 加一个click 事件,那么事件就会一层一层的往外执行,执行顺序 a > li > ul > div, 有这样一个机制,当我们给最外层的div 添加点击事件,那么里面的ul , li , a 做点击事件的时候,都会冒泡到最外层的div上,所以都会触发,这就是事件委托,委托他们父集代为执行事件;
总结
- 事件委托的意思就是子元素的事件会传播到父元素的回调方法,而不用单独给子元素绑定事件回调方法
十一、事件对象
- 禁用DOM默认事件
//禁用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." );
});
- 仅运行一次的事件,one方法与on方法具有一样的用法,只执行一次就是唯一的区别
// 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" );