The difference between assigning event handlers wi

2019-04-14 00:40发布

can someone tell me what the difference between assigning event handlers using bind():

$(function(){
           $('someElement')
           .bind('mouseover',function(e) {
            $(this).css({
                        //change color
                        });
    })
    .bind('mouseout',function(e) {
        $(this).css({
                    //return to previous state

                 });    
    })
    .bind('click',function(e) {
        $(this).css({
                    //do smth.
                 });    
    })

}); 

and using each() for the same task:

$('someElement').each(function(){

        $(this).mouseover(function(){$(this).css({/*change color*/})
                    .mouseout(function(){$(this).css({/*return to previous state*/});   
                    });     
                }); 
    });

thank you.

1条回答
放荡不羁爱自由
2楼-- · 2019-04-14 01:25

From the examples you gave, I think you're actually asking what the difference, if any, is there between using the 'bind' method and then 'event' methods.

For example, what's the difference between:

$('.some_element').bind('click',function() { /* do stuff */ });

... and this?

$('.some_element').click(function() { /* do stuff */ });

The answer is that it really doesn't matter. It's a matter of preference. The event methods are syntactically simpler and involve less typing, but, as far as I know there really isn't any difference. I prefer to use the bind methods because you can use shorthand event binding if you need to attach more than one event to the same action. It also makes it simpler to understand when/if you need to 'unbind' an event.

See here: Difference between .bind and other events

But, from what the actual question asks, "What's the difference between the 'each' method and the 'bind' method"... well, that's a totally different beast.

You should never really use the 'each' method to attach events because the 'bind' and 'event' methods use the much quicker CSS selector engine (in jQuery's case, it uses the Sizzle engine).

There's hardly ever (or never) a case where this:

$('.some_element').each(function() { $(this).click(function() { /* do something */ }); });

... is better than this:

$('.some_element').bind('click',function() { /* do stuff */ });
查看更多
登录 后发表回答