开发者

Are handlers always called synchronously during jQuery click()?

开发者 https://www.devze.com 2023-03-18 17:06 出处:网络
Through some brief testing it appears that cli开发者_C百科ck() will trigger any applicable handlers synchronously (that is, the handlers are all invoked before click() returns), which is desirable for

Through some brief testing it appears that cli开发者_C百科ck() 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消