为什么在jquery中使用bind或on而不是直接事件触发器?
我见过很多人使用bind或on函数而不是直接事件触发器等为什么在jquery中使用bind或on而不是直接事件触发器?,jquery,Jquery,我见过很多人使用bind或on函数而不是直接事件触发器等 $(document).bind('click', function(){ alert('Fired'); }); 而不是 $(document).click(function(){ alert('Fired'); }); 对于on函数也是一样的 $('p').on('click', function()({ alert('fired'); }); 而不是 $('p').click(functi
$(document).bind('click', function(){
alert('Fired');
});
而不是
$(document).click(function(){
alert('Fired');
});
对于on函数也是一样的
$('p').on('click', function()({
alert('fired');
});
而不是
$('p').click(function()({
alert('fired');
});
有人能解释一下吗
.click()
是('click',handler)上的.on的快捷方式。根本没有区别。因此,您最好坚持使用.on()
并保存额外的函数调用
从jQuery 1.7开始,.bind()
、.live()
和.delegate()
方法已被.on()
取代。这些函数将在jQuery的未来版本中删除。.on()
方法是将事件处理程序附加到文档的首选方法
在内部,jQuery将所有这些方法和速记事件处理程序设置程序映射到.on()
方法,进一步指出从现在起应该忽略这些方法,只使用.on()
:
我几乎可以在任何地方使用.bind或.on。我几乎从不使用。单击。原因如下:
如果您希望使您的网站或web应用程序跨平台兼容,并且希望用户在计算机上“单击”按钮,并在iPad或其他移动设备上“点击”按钮,则单击可能对您不利
我用这样的方式:
$("#myButton").on(inputType(), functionHandler(){console.log("you have clicked or touched myButton!"});
function inputType(){
if(getUserDevice != "computer"){
return "touchend";
}else{
return "click";
}
}
function getUserDevice(){
//code in here determine if it's a computer or a "touch device"
//return "computer";
}
然而,它们都是完全相同的东西,.on()
用于支持.live()
、.bind()
、和.delegate()
,因为上述两者之间存在的任何细微差别和错误都已修复并合并,以按预期执行。另外,与相反,使用.on()
并没有直接的好处。如果元素在页面加载时存在,并且您正在$(document.ready()
函数中委托事件,则单击()
。签出文档时,它们都会提到首选哪种方法以及哪种方法是另一种方法的捷径等等。基本上,在jQuery1.6-上使用bind()
if,在jQuery1.6-上使用delegate()
if,需要将事件绑定到动态元素,并在jQuery1.7+上使用on()
if,使用委托进行静态和动态元素绑定。
$("#myButton").on(inputType(), functionHandler(){console.log("you have clicked or touched myButton!"});
function inputType(){
if(getUserDevice != "computer"){
return "touchend";
}else{
return "click";
}
}
function getUserDevice(){
//code in here determine if it's a computer or a "touch device"
//return "computer";
}