【问题标题】:<a> onClick event but still proceed to href target<a> onClick 事件,但仍继续到 href 目标
【发布时间】:2012-06-10 22:08:33
【问题描述】:

我有一个链接如下:

<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 事件中输入 return false,但是当然 href 不会导航到目标。

如何让这两种方法都发挥作用?

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

【问题讨论】:

  • 您可以尝试使用 JavaScript 设置 window.location,作为 onclick 事件的一部分。
  • 据我所知,&lt;a&gt;onclickhref 属性是互斥的。只需将重定向作为 json 调用的一部分即可。
  • 汤姆说的可能会奏效。好奇,你为什么要注入一个脚本标签并离开(在同一个选项卡上)?脚本甚至无法加载...
  • 它是一个跟踪模块,注入的jsonp调用跟踪链接被点击。
  • @redolent Reactive UI,现在风靡一时。

标签: javascript html jsonp


【解决方案1】:

你应该阻止默认事件... 看那里: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;
} 

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

【讨论】:

  • 使用了此代码的简化版本(没有使用 preventdefault,只是“返回 false”)。 setTimeout() 是必需的,尽管我将其缩短为 50 毫秒。
【解决方案2】:
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://

【讨论】:

    【解决方案3】:

    试试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-16
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      • 2012-01-23
      • 2011-04-24
      相关资源
      最近更新 更多