2015-05-05 40 views
5

我在這裏得到了幫助,將這些代碼放在一起。它在Chrome,Safari和Internet Explorer中完美運行。但在Firefox它重定向到一個子URL(它可能不是正確的字......)如何讓這個JavaScript重定向在Firefox中工作?

我有一個頁面上的腳本:

http://example.com/test

enter image description here

而且我想根據用戶選擇的值重新定向到一個新頁面(然後單擊按鈕):因此,如果我選擇選項#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使用這些framworks時發生錯誤。

下面是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:

Here is a fiddle

你看到的原因Firefox的表現也是這樣嗎?

如果感興趣:我在Mac OSX 10.10.2使用Chrome 42.0.2311.90(64位),火狐37.0.2和Windows 8.1 IE 11.09600.17728

+0

'你看到爲什麼Firefox的行爲像這樣'你應該使用瀏覽器控制檯真的調試代碼,這將是非常固定的真的很快 –

回答

12

您已經使用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()); 
}); 
+0

嗎?謝謝。我剛剛在小提琴中進行了測試,並在那裏工作。去測試我的網站。謝謝羅裏。 http://fiddle.jshell.net/Preben/s3pv5t3g/3/ – Preben

+0

我只是確認這也適用於我的網站。我會選擇這個作爲我的答案,但現在爲時尚早。 (我還沒準許。) – Preben

+0

沒問題,很樂意幫忙。 –

0

你有一個錯誤你的JS。變量事件未定義。 嘗試這樣的:

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