<a> onClick event but still proceed to href target</a>

时间:2012-06-06 20:39:07

标签: javascript html jsonp

我的链接如下:

<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调用从未实际执行过,除非我将返回false设置为onlick事件,但当然href不会导航到目标。

我如何让两件事都起作用?

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

3 个答案:

答案 0 :(得分:2)

你应该防止默认事件......   看那里:event.preventDefault类似的东西......

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;
} 

Personnaly,我真的不喜欢使用内联onclick属性,我会使用addEventListener或attachEvent ...我认为这是一种方式:)

答案 1 :(得分:0)

function runSomeJsonpCall(obj) {
    //...
    document.location=obj.getAttribute('href');
    return false;
}

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

另请注意http:// in href link

答案 2 :(得分:-1)

尝试:

<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");
}
相关问题