jQuery Html 锚标记 onclick() 和 href 同时执行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19250645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html anchor tag onclick() and href execute simultaneously
提问by CheeHow
Similar to HTML anchor link - href and onclick both?post, mine is:
类似于HTML 锚链接 - href 和 onclick 两者?帖子,我的是:
<a href="/tmp/download.mp3" onclick="update();">Download link</a>
The update()
method would send another HTTP GET method to the server to update the which file has been downloaded and update the database. From the HTML code, there are 2 GET requests being triggered together and only ONE will get the response (the href download response) from the server. The update()
is not being executed. Is there any method that i can get both GET methods to be executed? Javascript and Jquery suggestions are welcomed!
该update()
方法将向服务器发送另一个 HTTP GET 方法以更新已下载的文件并更新数据库。从 HTML 代码来看,有 2 个 GET 请求被一起触发,只有一个会从服务器获得响应(href 下载响应)。在update()
没有被执行。有什么方法可以让我同时执行两个 GET 方法?欢迎 Javascript 和 Jquery 建议!
回答by musefan
Forget about the href
and just do it all in the click function. You can navigate to another page after the update is complete. Here is my JQuery suggestion:
忘记href
,只需在点击功能中完成所有操作。更新完成后,您可以导航到另一个页面。这是我的 JQuery 建议:
HTML
HTML
<a id="download" href="/tmp/download.mp3">Download link</a>
JavaScript (with JQuery)
JavaScript(使用 JQuery)
$("#download").click(function(e){
e.preventDefault();//this will prevent the link trying to navigate to another page
var href = $(this).attr("href");//get the href so we can navigate later
//do the update
//when update has finished, navigate to the other page
window.location = href;
});
NOTE: I added in an id
for the a
tag to ensure it can be selected accurately via JQuery
注意:我添加了一个id
fora
标签以确保它可以通过 JQuery 准确选择