The difference between assigning event handlers with bind() and each() in jQuery?

隐身守侯 提交于 2019-12-06 09:57:33

问题


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:


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 */ });


来源:https://stackoverflow.com/questions/756547/the-difference-between-assigning-event-handlers-with-bind-and-each-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!