JQuery中对事件的支持尤为强大,这里只做简单的介绍,详细的资料还是要去官方站点获取。
1.绑定事件
function testA(event){
alert( event.data.msg);
}
$("div").bind("click mousedown",{msg: message},testA}; //将testA绑定到<div>的click事件上,并传入变量message
1.1分别将不同的eventhandler绑定到不同的事件上
function testA(){}
function testB(){}
function testC(){}
$("div").bind({click:testA,mousedown:testB})
1.2绑定的事件中加入namespace
function testA(){}
function testB(){}
$("div").bind("click",testA);
$("div").bind("click.snake",testB); //将testB绑定到snake中的click
完成绑定后,点击鼠标,即可出发testA和testB
$("div").unbind(".snake"); //将snake中的所有click解除绑定。
2.trigger
$('#foo').bind('custom', function(event, param1, param2) { alert(param1 + "/n" + param2);});
$('#foo').trigger('custom', ['Custom', 'Event']);
$('#foo').trigger("click.snake") //触发namespace 为snake的click事件
3.event object
JQuery会向event handler传送event object
通过event object,可以获得很多环境变量,而且传入的参数也可以在event object找到,如上面的例子。由于篇幅所限,我们不一一列出 event object 的方法和属性,请查阅官方文档
4.live和die
在上面介绍的事件绑定方法都是在定义期就需要明确的,但是在实际应用中,如果动态添加一个dom节点后,也需要根据定义将事件动态绑定到它的上面。这里就需要利用live()方法了
$('.clickme').live('click', function() {// Live handler called.});
$('body').append('<div class="clickme">Another target</div>');
这里有JQuery对live工作原理的简介:
- A click event is generated and passed to the
<div>
for handling. - No handler is directly bound to the
<div>
, so the event bubbles up the DOM tree. - The event bubbles up until it reaches the root of the tree, which is where
.live()
binds its special handlers by default. - The special
click
handler bound by.live()
executes. - This handler tests the
target
of the event object to see whether it should continue. This test is performed by checking if$(event.target).closest('.clickme')
is able to locate a matching element. - If a matching element is found, the original handler is called on it.
die()函数是用来解除live()绑定的事件
5.方便的hover 和 toggle
hover( handlerIn(eventObject), handlerOut(eventObject) )
handlerIn(eventObject) A function to execute when the mouse pointer enters the element.
handlerOut(eventObject) A function to execute when the mouse pointer leaves the element.
.toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] )
//Bind two or more handlers to the matched elements, to be executed on alternate clicks.
.toggle( [ duration ], [ callback ] )
// Display or hide the matched elements.
$("p").toggle("slow");
$("p").toggle( flip++ % 2 == 0 );