同时使用<href>链接和<点击>功能

Use <a href> link and <onclick> function together

本文关键字:链接 点击 功能 href      更新时间:2023-09-26

如何使它成为与href和onClick函数一起使用的标签?(onClick 应该先运行,然后再运行 href)

版本 1

<a href="#" id="myHref">Click me</a>
$("#myHref").on('click', function() {
    document.getElementById(".myDiv").style.flexGrow = "5";
     window.location = "http://www.google.com";
});

版本 2

 <a href="http://www.google.com" onclick="return myFunction();">Link</a>
function myFunction() {
    document.getElementById(".myDiv").style.flexGrow = "5"; 
}

您需要取消点击,调用动画,然后添加延迟以点击链接。

$("#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
});

设置超时将允许动画发生。将时间调整为任何有效的时间。

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")

您可以使用版本 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;
});