【问题标题】:How to temporary disable the click function when it is executing?如何在执行时暂时禁用点击功能?
【发布时间】:2013-03-05 04:48:36
【问题描述】:
$("#prevPage").live("click",function(e) {
.................
});

例如,当用户已经点击了prevPage,里面的语句正在运行,如果用户立即点击,它会再次触发。但是,我希望只有在它里面的所有语句都执行完之后才触发点击事件,如何实现呢?

【问题讨论】:

  • 使用 .on() 而不是 .live() 因为 .live() 已弃用..

标签: javascript jquery mouseevent jquery-events


【解决方案1】:

这个或类似的东西怎么样:

<script type="text/javascript">
    // disable command while function is being executed.
    var sample = { 
        isExecuting : 0, 
        doWork : function (e) { 
            if (sample.isExecuting === 1) return;
            sample.isExecuting = 1;
            // do work -- whatever you please
            sample.isExecuting = 0; // say: I'm done!
        }
    };
    // live or bind
    $("#prevPage").bind("click",function(e) {
         sample.doWork(e);
    });
</script>

简单的“屏蔽”来阻止多呼叫场景。

【讨论】:

  • 如果有像 settimeout 这样的异步执行,在“做事——随心所欲”。
  • 然后你推迟“取消标记”(sample.isExecuting = 0)直到操作完成。你的异步操作中有回调函数吗?
  • 异步 ajax 或工作线程?我将提供一个代码示例。在所有异步场景中,有时某些操作需要同步发生。了解适用于何处是应用程序开发的先决条件。等待反馈
【解决方案2】:

然后在元素上设置一个标志来检查它是否可以点击。

$("#prevPage").on("click",function(e) {

  e.preventDefault();

  //get the clickable attribute
  //if it's not existent, its undefined hence "false"
  var unclickable = this.unclickable;

  //if it's not unclickable (it's clickable)
  if(!unclickable){

    //make the flag unclickable
    this.unclickable = true;

    //do stuff

    //reset it back the way it was after operations
    this.unclickable = false;
  }


});

【讨论】:

    【解决方案3】:

    设置一个你的事件触发的变量

    var prevPageEventTriggered = false ;
    

    并在事件触发时将其设置为ture

    prevPageEventTriggered = true;
    

    然后在点击事件处理函数中为此添加条件

    $("#prevPage").live("click",function(e) {
    
            if ( prevPageEventTriggered ) {
                    return false;
            }
    
            // your code goes here
            // ....
    });
    

    如果它已经完成执行,您可以将其设置为 false 。希望这会有所帮助

    【讨论】:

      【解决方案4】:

      使用jquery的unbind功能

      $("#prevPage").unbind("click");
      

      任务完成后

      $("#prevPage").bind("click",function(){....your code here....});
      

      【讨论】:

      • 您应该使用die,但要知道livedie 在jQuery 1.9 中已被删除
      • $("#prevPage").bind("click",function(){});
      【解决方案5】:
      • unbind() 将为您完成这项工作。

      • 替代方法可能类似于使用 detach()。当您的进程正在执行分离按钮并且当您的进程完成执行时,使用 reattach() 来取回按钮。 我建议使用 unbind()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-29
        • 1970-01-01
        • 1970-01-01
        • 2017-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多