<a> onClick 事件,但仍继续执行 href 目标

<a> onClick event but still proceed to href target

本文关键字:继续 href 目标 执行 事件 onClick      更新时间:2023-09-26

我有一个链接如下:

<a onclick="runSomeJsonpCall();" href="www.goherenext.com"> make this work </a>

javascript 方法执行基本的 JSONP 调用,如下所示:

function runSomeJsonpCall() {
var script = document.createElement("script");
script.src = "http://jsonpurl.com?parameter1=" + "someparam";
document.body.appendChild(script);
}

我的 JSONP 调用从未实际执行,除非我向 onlick 事件返回 false,但当然 href 不会导航到目标。

如何使这两件事都起作用?

注意:我只能使用纯JavaScript,没有库

您应该阻止默认事件... 看那里:事件.预防默认类似的东西...

function runSomeJsonpCall(event) {
    if (!event) var event = window.event;
    if (event.preventDefault) {
       event.preventDefault();
    }else{
       // IE
       event.returnValue = false;
    }
    var script = document.createElement("script");
    script.src = "http://jsonpurl.com?parameter1=" + "someparam";
    document.body.appendChild(script);
   // you should wait for jsonp loading
   // here i use an ID to retreive  the element but you can do your way ...
   setTimeout("changeLocation('"+ document.getElementById('linkID').href +"')", 1000);
}
changeLocation(location) {
    window.location.href = location;
} 

就个人而言,我真的不喜欢使用内联点击属性,我会使用 addEventListener 或 attachEvent ...我认为这是一种更糟糕的方式:)

function runSomeJsonpCall(obj) {
    //...
    document.location=obj.getAttribute('href');
    return false;
}
<a onclick="runSomeJsonpCall(self);" href="http://www.goherenext.com"> make this work </a>

另请注意 href 链接中的 http://

尝试:

<a onclick="runSomeJsonpCall();" href="#"> make this work </a>

和:

function runSomeJsonpCall() {
var script = document.createElement("script");
script.src = "http://jsonpurl.com?parameter1=" + "someparam";
document.body.appendChild(script);
window.location("www.goherenext.com");
}