即使在onclick ="return false;"之后,IE也会跟踪链接. [英] IE Follows Link Even After onclick="return false;"

查看:108
本文介绍了即使在onclick ="return false;"之后,IE也会跟踪链接.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Rails 2.3.8应用程序,并使用标准的link_to帮助器.除了GET以外,我还有很多其他用户方法可以使用的用户链接,因此我将:method => :whatever选项传递给link_to,它会生成一个带有onclick处理程序的链接,如下所示(为提高可读性而添加了缩进):

I'm writing a Rails 2.3.8 app, and using the standard link_to helper. I have a reasonable number of links that user methods other than GET, so I pass a :method => :whatever option to link_to, and it generates a link with an onclick handler like so (indentation added for readability):

<a
  onclick="
    var f = document.createElement('form');
    f.style.display = 'none';
    this.parentNode.appendChild(f);
    f.method = 'POST';
    f.action = this.href;
    var s = document.createElement('input');
    s.setAttribute('type', 'hidden');
    s.setAttribute('name', 'authenticity_token');
    s.setAttribute('value', '31M3q8SJkRz7f0R80l42Z2W7O2N7ZrzufhWQYql/Zd8=');
    f.appendChild(s);
    f.submit();
    return false;"
  href="/transactions/1015/transcribe"
>
Enter Data
</a>

现在,无论出于何种原因,IE(都是7和8-我已经测试过的两个)都认为return false;末尾不足以阻止它跟随链接,所以我结束了最多收到两个请求到我的服务器:来自onclick处理程序的POST请求(我想要的)和来自链接本身的GET请求(我不需要).实际上,除了POST请求外,该路由不存在,因此当浏览器遵循GET请求时,用户将被转储到错误URL"错误屏幕上.不好.

Now, for whatever reason, IE (both 7 & 8 - the two I've tested) has decided that the return false; at the end there isn't enough to stop it from following the link, and I end up getting two requests to my server: The POST request from the onclick handler, which I want, and the GET request from the link itself, which I don't. In fact, that route doesn't exist for anything other than a POST request, so when the browser follows the GET request, the user gets dumped on a 'Bad URL' error screen. Not good.

以前有没有人看过这个,可以告诉我是什么原因造成的?或者,更好的是,有人知道一个好的解决方法吗?

Has anyone seen this before, and can tell me what's causing it? Or, better yet, does anyone know a good workaround?

PS:我宁愿

  1. 猴子补丁link-to
  2. 编写我自己的link_to
  3. 版本
  1. Monkey-patch link-to, or
  2. Write my own version of link_to

但是,如果那是需要的,那就是它的需要.而且我正在使用jQuery 1.5.something,如果有帮助的话.

but if that's what it takes, that's what it takes. And I'm using jQuery 1.5.something, if that helps.

推荐答案

为防止在JQuery中提交表单,我们经常使用

To prevent form submission in JQuery, we often use

event.preventDefault();

因此,在您的示例中,您可以使用它(如注释中所述):

So in your example, you could use this (as discussed in comments) :

$('a[onclick]').click(function(e) {e.preventDefault();});

希望有帮助!

这篇关于即使在onclick ="return false;"之后,IE也会跟踪链接.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆