【问题标题】:How to get this javascript redirect to work in Firefox?如何让这个 javascript 重定向在 Firefox 中工作?
【发布时间】:2015-05-05 18:12:32
【问题描述】:

我在这里得到了帮助来整理这段代码。它在 Chrome、Safari 和 Internet Explorer 中完美运行。但在 Firefox 中,它会重定向到一个子 URL(可能不是正确的词......)

我在页面上有脚本:

http://example.com/test

我想根据用户选择的值重定向到一个新页面(然后单击按钮):所以如果我选择选项 #2 我想到达这里:http://example.com/my-test-2

它适用于其他浏览器,但不适用于 Firefox。在 Firefox 中,它改为重定向到: http://example.com/test?redirect=http%3A%2F%2Fexample.com%2Fmy-test-2 这当然不会导致任何地方。

HTML 是在 jquery 和 Bootstrap 环境中加载的,我确实在该页面上使用了模式。我只是提到这一点,以防 Firefox 使用这些框架时出现已知错误。

这是 HTML:

I want to choose:
<form  id="mychoice">
    <input type="radio" name="redirect" value="http://example.com/my-test-1"><span>1</span><br>
    <input type="radio" name="redirect" value="http://example.com/my-test-2"><span>2</span><br>
    <input type="radio" name="redirect" value="http://example.com/my-test-3"><span>3</span><br>
    <input type="radio" name="redirect" value="http://example.com/my-test-4"><span>4</span><br>
    <input type="radio" name="redirect" value="http://example.com/my-test-5"><span>5</span><br /><br />
    <input type="submit" value="See result">
</form>

javascript:

$(document).ready(function(){    
    $("#mychoice").submit(function(){
        event.preventDefault();
        var loc = $('input[name="redirect"]:checked').val();
        window.location = loc;
        return false;    
    });
});

Here is a fiddle

你明白 Firefox 出现这种行为的原因吗?

如果有兴趣:我在 Mac OSX 10.10.2 上使用 Chrome 42.0.2311.90(64 位)、Firefox 37.0.2 和 Windows 8.1 IE 11.09600.17728

【问题讨论】:

  • Do you see the reason why Firefox behaves like this? 你真的应该使用浏览器控制台调试你的代码,这会很快解决

标签: javascript jquery firefox


【解决方案1】:

您已经使用了preventDefault(),但实际上并没有将event 传递给处理程序。另请注意,使用window.location.assign() 是更好的做法。试试这个:

$("#mychoice").submit(function(event) { // < 'event' is the parameter passed to the func
    event.preventDefault();
    window.location.assign($('input[name="redirect"]:checked').val());
});

【讨论】:

  • 谢谢。我刚刚在小提琴中进行了测试,它在那里工作。打算在我的网站上测试。谢谢你罗里。 fiddle.jshell.net/Preben/s3pv5t3g/3
  • 我只是确认这在我的网站上也有效。我会选择这个作为我的答案,但现在还为时过早。 (目前还不允许。)
  • 没问题,很乐意提供帮助。
【解决方案2】:

你的 JS 有错误。变量事件未定义。 试试这样:

$(document).ready(function(){
    $("#mychoice").submit(function(event){
        event.preventDefault();
        var loc = $('input[name="redirect"]:checked').val();
        window.location.href = loc;
        return false;    
    });
});

【讨论】:

    猜你喜欢
    • 2016-08-18
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2013-10-09
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多