【问题标题】:How to bind an event only after it loses binding before如何仅在事件之前失去绑定之后才绑定事件
【发布时间】:2013-03-23 18:08:31
【问题描述】:

我有一个 div 绑定click,如下所示:

  $("#mydiv").one('click',function(){ ... });

因为我只想执行一次操作。 现在我想重新bind

  $("#mydiv").on('click',function(){ ... });

但只有当用户点击它时,至少是第一次。

我该怎么做?

【问题讨论】:

  • 你的意思是,第一次点击给出action-A,然后后续点击给出action-B?
  • 没错,我必须执行一个追加然后我就不再需要了。

标签: javascript jquery events binding


【解决方案1】:

您可以使用 jQuery namespace events

$('#mydiv').on('click.firstClick', function () {
    // do stuff for the first time
    $(this).off('click.firstClick'); // only removes this event
});

$('#mydiv').on('click', function () {
    // stuff that always happens when you click
});

如果你只是想让某事第一次发生,然后每次都发生某事:

$('#mydiv').click(function () {
    // stuff that happens the first time you click
    $(this).off('click');
    $(this).click(function () {
        // stuff that happens every time after this
    });
});

第一种情况的示例:http://jsfiddle.net/75HWV/ 第二种情况示例:http://jsfiddle.net/SbhY3/

【讨论】:

  • 我要试试,几分钟后告诉你。我想它会成功的。
【解决方案2】:
$('#mydiv').one('click', function() {
    // ...
    // code here for action-A, on first click
    // ...
    $(this).on('click', function() {
        // ...
        // code here for action-B, on subsequent clicks
        // ...
    });
});

【讨论】:

    猜你喜欢
    • 2011-08-25
    • 2012-06-07
    • 1970-01-01
    • 2023-03-07
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    相关资源
    最近更新 更多