【问题标题】:The difference between assigning event handlers with bind() and each() in jQuery?在 jQuery 中使用 bind() 和 each() 分配事件处理程序的区别?
【发布时间】:2010-10-19 21:13:18
【问题描述】:

谁能告诉我使用 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.
            });
        })
});

将 each() 用于相同的任务:

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

【问题讨论】:

  • 您的第二个示例没有演示“每个”方法。只是让你知道......

标签: javascript jquery function bind each


【解决方案1】:

从您提供的示例中,我认为您实际上是在问使用“绑定”方法和“事件”方法之间有什么区别(如果有的话)。

例如,有什么区别:

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

...还有这个?

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

答案是真的没关系。这是一个偏好问题。事件方法在语法上更简单,涉及的输入更少,但是,据我所知,确实没有任何区别。我更喜欢使用绑定方法,因为如果您需要将多个事件附加到同一个操作,您可以使用速记事件绑定。它还使您更容易理解何时/是否需要“取消绑定”事件。

请看这里:Difference between .bind and other events

但是,从实际的问题来看,“'each' 方法和 'bind' 方法有什么区别”......好吧,那是完全不同的野兽。

你永远不应该真正使用 'each' 方法来附加事件,因为 'bind' 和 'event' 方法使用 much 更快的 CSS 选择器引擎(在 jQuery 的情况下,它使用 Sizzle 引擎)。

几乎从来没有(或从来没有)这样的情况:

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

...比这更好:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 2013-06-26
    • 2015-11-18
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多