如何让这个 javascript 重定向在 Firefox 中工作?

How to get this javascript redirect to work in Firefox?

我在这里得到了帮助来整理这段代码。它在 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

您使用了 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());
});

你的 JS 出错了。未定义变量事件。 像那样尝试:

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