开发者

Does javascript still execute if I navigate to a different page?

Say I have a set-up like this:

$('#mylink').click(function(event){
   savePost();
});

<a id="mylink" href="http://google.com">my link</a>

If I click the link will I be gone to a different page without giving the function a chance to execute?开发者_如何学运维

What if savePost() has ajax and a callback function? Will it execute regardless of what page the browser is on when the script executes? (or would I have to preventDefault on the link and put the window.location command within the callback)


Script will be executed first, then window.location


Yes,

onclick script will be executed before changing window.location

on ajax callback, i don't think so, as ajax and callback are asynchronous calls,
so if you need to navigate only after success perform of ajax call use complete(jqXHR, textStatus) callback on jQuery.ajax() together with preventDefault()

see http://api.jquery.com/jQuery.ajax/


Call event.preventDefault(); to prevent the link from actually changing the page. Otherwise the page will change after the onclick function has been executed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜