在jQuery click()期间,处理程序是否总是同步调用? [英] Are handlers always called synchronously during jQuery click()?

查看:479
本文介绍了在jQuery click()期间,处理程序是否总是同步调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过一些简短的测试,似乎 click()将触发任何适用的处理程序同步(即处理程序都在 click()返回),这对我正在开发的是可取的。但是,jQuery文档似乎不能保证(不提及一种方式)处理程序被同步调用。



同步行为是否保证在某个地方,或以其他方式安全地假定为跨浏览器和面向未来?

$ b $是的,在幕后,所有的点击事件将在正常的默认功能启动之前同步运行。一个看到这个动作的方法是添加一个或者更多点击事件到锚标签。如果任何附加的函数返回false。它将取消锚标签的默认功能。换句话说,你不会去 href 属性中的页面。

  $(a:first)
.click(function(){alert(I've attached first!); return false;})
.click(function() alert(尽管早期运行return false'!);});

您会注意到,它们以同样的顺序运行,并且以相同的顺序运行!任何附加的函数都可以返回false以取消锚标签发生的正常重定向。



当使用jQuery触发点击事件,所有附加的函数将在执行其余链接操作之前运行。

  $(a :第一个)
.click(function(){alert(I was attached first!); return false;})
.click(function(){alert( return false'!);});
$(a:first)。click()。css(color,red);

所以,上面的代码将始终显示两个警报,然后将链接颜色更改为红色。 p>

Through some brief testing it appears that click() will trigger any applicable handlers synchronously (that is, the handlers are all invoked before click() returns), which is desirable for what I'm developing. However, the jQuery documentation does not seem to guarantee (does not mention one way or the other) that handlers are invoked synchronously.

Is a synchronous behavior guaranteed somewhere, or otherwise safe to assume as cross-browser and future-proof?

解决方案

Yes, behind the scenes all the click events will run synchronously before the normal default functionality kick in. One way to see this in action is to add one or more click events to an anchor tag. If any of the attached functions return false. It will cancel the default functionality of the anchor tag. In other words, you won't go to the page in the href attribute.

$("a:first")
    .click(function() { alert("I was attached first!"); return false; })
    .click(function() { alert("Running despite the earlier 'return false'!");});

You'll notice that they run synchronously and in the same order they were attached! Any of the attached functions can return false to cancel the normal redirect that happens with anchor tags.

When using jQuery to trigger the click event, all the attached functions will run before the rest of the chained actions are performed.

$("a:first")
    .click(function() { alert("I was attached first!"); return false; })
    .click(function() { alert("Running despite the earlier 'return false'!");});
$("a:first").click().css("color", "red");

So, the code above will ALWAYS show the two alerts then change the link color to red.

这篇关于在jQuery click()期间,处理程序是否总是同步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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