我如何等待点击事件完成 [英] How can I wait for a click event to complete

查看:123
本文介绍了我如何等待点击事件完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将click事件处理程序添加到元素

I add a click event handler to an element

 $(".elem").click(function(){
       $.post("page.php".function(){
         //code1
      })
 })

然后我触发点击事件

$(".elem").click();
//code2

如何确保在执行代码1之后执行代码2

How can i make sure that code2 executes after code1 executes

推荐答案

(忽略WebWorkers)JavaScript在单个线程上运行,因此可以确保code2将始终在code1之后执行.

(Ignoring WebWorkers) JavaScript runs on a single thread, so you can be sure that code2 will always execute after code1.

除非,您的代码1执行异步操作,例如Ajax调用或setTimeout(),在这种情况下,触发的单击处理程序将完成,然后代码2将执行,然后(最终)从Ajax进行回调呼叫(或setTimeout()或其他任何内容)将运行.

Unless your code1 does something asynchronous like an Ajax call or a setTimeout(), in which case the triggered click handler will complete, then code2 will execute, then (eventually) the callback from the Ajax call (or setTimeout(), or whatever) will run.

对于您更新的问题,代码2将始终在代码1之前执行,因为正如我在上面所说,异步Ajax回调将在以后发生(即使Ajax响应非常快,也不会调用回调,直到当前JS完成为止.

For your updated question, code2 will always execute before code1, because as I said above an async Ajax callback will happen later (even if the Ajax response is very fast, it won't call the callback until the current JS finishes).

在代码1执行后如何确保代码2执行"

使用不带参数的.click().trigger("click")的快捷方式,但是如果您实际调用.trigger(),则可以提供将传递给处理程序的其他参数,从而可以做到这一点:

Using .click() with no params is a shortcut to .trigger("click"), but if you actually call .trigger() explicitly you can provide additional parameters that will be passed to the handler, which lets you do this:

$(".elem").click(function(e, callback) {
    $.post("page.php".function(){
      //code1

      if (typeof callback === "function")
         callback();
   });
});

$(".elem").trigger("click", function() {
    // code 2 here
});

也就是说,在点击处理程序中,测试是否已在callback参数中传递了函数,如果是,则进行调用.这意味着当事件自然地"发生时,将没有回调,但是当您以编程方式触发它并传递一个函数时,该函数将被执行. (请注意,通过.trigger()传递的参数不必是一个函数,它可以是任何类型的数据,并且可以传递多个参数,但是为此,我们需要一个函数.请参见 .trigger() doco 了解更多信息.)

That is, within the click handler test whether a function has been passed in the callback parameter and if so call it. This means when the event occurs "naturally" there will be no callback, but when you trigger it programmatically and pass a function then that function will be executed. (Note that the parameter you pass with .trigger() doesn't have to be a function, it can be any type of data and you can pass more than one parameter, but for this purpose we want a function. See the .trigger() doco for more info.)

演示: http://jsfiddle.net/nnnnnn/ZbRJ7/1/

这篇关于我如何等待点击事件完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆