Html锚点标签onclick()和href同时执行 [英] Html anchor tag onclick() and href execute simultaneously

查看:135
本文介绍了Html锚点标签onclick()和href同时执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于 HTML定位链接 - href和onclick两者? post,mine是:

 < a href =/ tmp / download.mp3onclick =update(); >下载链接< / a> 

update()方法会发送另一个通过HTTP GET方法向服务器更新已下载的文件并更新数据库。从HTML代码中,有2个GET请求被一起触发,只有一个会从服务器获得响应(href下载响应)。 update()没有被执行。有什么方法可以让我的GET方法被执行吗?欢迎使用Javascript和Jquery的建议!

解决方案

忘记 href 和只需在点击功能中完成所有操作。更新完成后,您可以导航到另一个页面。这是我的JQuery建议:

HTML

 < a id =下载href =/ tmp / download.mp3>下载链接< / a> 

JavaScript(带有JQuery)

<$ p $点击(函数(e){
e.preventDefault(); //这将阻止链接尝试导航到另一页面
var href = $(this).attr(href); //获取href,以便稍后导航

//执行更新

//更新时已完成,导航到其他页面
window.location = href;
});

注意:我在 id 中添加了 a 标记以确保可以通过JQuery精确选择

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!

解决方案

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

这篇关于Html锚点标签onclick()和href同时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆