How to make this a tag working with href and onClick function? (The onClick should run first then href)
Version 1
<a href="#" id="myHref">Click me</a>
$("#myHref").on('click', function() {
document.getElementById(".myDiv").style.flexGrow = "5";
window.location = "http://www.google.com";
});
Version 2
<a href="http://www.google.com" onclick="return myFunction();">Link</a>
function myFunction() {
document.getElementById(".myDiv").style.flexGrow = "5";
}
答案 0 :(得分:2)
您需要取消点击,调用动画,然后添加延迟以关注该链接。
$("#myHref").on('click', function(evt) {
evt.preventDefault(); //cancel the default click action
document.getElementById(".myDiv").style.flexGrow = "5";
var url = this.href; //get the href of the clicked link
window.setTimeout( function () { //delay setting the location
window.location.href = url;
}, 5000); //number of milliseconds to wait
});
setTimeout将允许动画发生。调整任何工作的时间。
答案 1 :(得分:-1)
href
不是一个事件,所以我不确定你的意思。
您的onclick
先运行,但如果您不想激活href,则应return false
。
版本1
$("#myHref").on('click', function() {
document.getElementById(".myDiv").style.flexGrow = "5";
window.location = "http://www.google.com";
return false;
});
此外,document.getElementById(".myDiv")
名称中不应包含点。 (假设你想得到<div id="myDiv">
。如果你有jQuery,只需使用$("#myDiv")
。
答案 2 :(得分:-1)
您可以使用版本1,只需将`event.preventDefault()'添加到处理程序:
<a href="http://www.google.com" id="myHref">Click me</a>
$("#myHref").on('click', function(event) {
event.preventDefault();
document.getElementById(".myDiv").style.flexGrow = "5";
window.location = event.currentTarget.href;
});