当处理div的点击时,使用.on和.click:
之间的区别 $('#myDiv').on('click' , function(e) {
});
$('#myDiv').click(function(e) {
});
答案 0 :(得分:2)
两者都相同......
.click
内部会调用.on
方法。
如果你看到jQuery源代码的这一部分。
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
您可以看到所有方法都依次调用.on
方法。因此,将降低您的一个级别。
这是jQuery中.on
的实现。
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {.....
答案 1 :(得分:1)
后者是第一个的快捷方式。
.on
更“低级别”并且更灵活。您可以将事件的第二个参数约束添加到选择器,例如:
$('#myDiv').on('click' , "span.icon", function(e) {
// this event will be fired when a click is made on a span.icon inside the #myDiv
});
答案 2 :(得分:0)
根据docs,从jQuery 1.7 .click()开始:
此方法是
.bind("click", handler)
的快捷方式,也是。{.on("click", handler)