Are handlers always called synchronously during jQuery click()?

前提是你 提交于 2019-12-06 04:39:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6620010/are-handlers-always-called-synchronously-during-jquery-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!