Html anchor tag onclick() and href execute simultaneously

柔情痞子 提交于 2020-01-29 06:09:46

问题


Similar to HTML anchor link - href and onclick both? post, mine is:

<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!


回答1:


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:

HTML

<a id="download" href="/tmp/download.mp3">Download link</a>

JavaScript (with 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



来源:https://stackoverflow.com/questions/19250645/html-anchor-tag-onclick-and-href-execute-simultaneously

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