var button1 = $('#button1'),
button2 = $('#button2'),
button3 = $('#button3'),
clear = $('#clear'),
div = $('#eventDiv');
div.on({
jump : function(){
alert('Jumped!');
},
punch : function(e,data){
alert('Punched '+data+'!');
},
click : function(){
alert('Simulated click!');
}
});
button1.click(function(){
div.trigger('jump');
});
button2.click(function(){
// Pass data along with the event
div.trigger('punch',['hard']);
});
button3.click(function(){
div.trigger('click');
});
clear.click(function(){
//some clear code
});
12.触摸事件
// Define some variables
var ball = $('<div id="ball"></div>').appendTo('body'),
startPosition = {}, elementPosition = {};
// Listen for mouse and touch events
ball.on('mousedown touchstart',function(e){
e.preventDefault();
// Normalizing the touch event object
e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;
// Recording current positions
startPosition = {x: e.pageX, y: e.pageY};
elementPosition = {x: ball.offset().left, y: ball.offset().top};
// These event listeners will be removed later
ball.on('mousemove.rem touchmove.rem',function(e){
e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;
ball.css({
top:elementPosition.y + (e.pageY - startPosition.y),
left: elementPosition.x + (e.pageX - startPosition.x),
});
});
});
ball.on('mouseup touchend',function(){
// Removing the heavy *move listeners
ball.off('.rem');
});
13.更快的阻止默认事件
通常,我们用event.preventDefalut()来阻止默认事件,但是jquery为此提供了更简便的方法:
<a href="http://google.com/" id="goToGoogle">Go To Google</a>
$('#goToGoogle').click(false);14.使用event.result链接多个事件处理程序。
对一个元素绑定多个事件处理程序并不常见,而使用event.result更可以将多个事件处理程序联系起来。看下面的例子。
var press = $('#press');
press.on('click',function(){
return 'Hip';
});
press.on('click',function(e){
console.log(e.result + ' Hop!');
})
//控制台输出: HipHop!
15.平行的运行多个Ajax请求
当我们需要发送多个Ajax请求是,相反于等待一个发送结束再发送下一个,我们可以平行地发送来加速Ajax请求发送。
$.when($.get('assets/misc/1.json'), $.get('assets/misc/2.json')).then(function(r1, r2){










