2012-12-08 40 views
1

我這樣做代碼: index.php文件重定向JQuery的

<html> 
<head> 
<title>Jeu de dammes</title> 
</head> 
<style> 
form { margin-left:500px;margin-top:300px; width:300px } 
    </style> 
<body> 
<form id="formulaire" style="margin-left:100px, padding: 15px" > 
<table> 
<tr><td><h4> The first player</h4></td> 
    <td><input type="text" id="premier"></td> 
</tr> 
<tr><td><h4> The second player</h4></td> 
    <td><input type="text" id="deuxieme"></td> 
</tr> 
<tr> 
<td></td> 
<td> 
<button id="action">Play</button></td> 
</tr> 
</table> 
</form> 
<script src="jquery-1.5.1.js"></script> 
<script> 

    $(function() { 

     $('#action').click(function() { 

      var j1= $('#premier').val(); 
      var j2= $('#deuxieme').val(); 

      if(j1=="") alert('saisir le nom du premier joueur'); 
      if(j2=="") alert('saisir le nom du deuxieme joueur'); 
      if(j2!="" && j1!="") {$(location).attr('href',"http://www.google.com");} 
     }); 

    $('body').css('background-image', 'url(flower2.jpg)').css('background-size', '100%'); 
    $("#formulaire").css('background-image', 'url(flower.jpg)'); 
    }); 
</script> 
</body> 
</html> 

我的問題是在事件點擊重定向到「www.google.com」不work.any建議:

  1. 這個錯誤的原因是什麼?
  2. 我該如何糾正它?
+1

那麼,沒有警報,沒有重定向?控制檯中有任何日誌? –

回答

1

有沒有必要使用jQuery做一些事情,香草的JavaScript已經這樣做了:

window.location.href = "http://www.google.com/"; 

它可能不工作,因爲你使用的是形式和提交之前,你可以重定向。抓住submit事件:

你的代碼改成這樣,它會工作:

$('#formulaire').submit(function(e) { 
    var j1 = $('#premier').val(); 
    var j2 = $('#deuxieme').val(); 

    if (j1 == "") { 
     alert('saisir le nom du premier joueur'); 
    } 

    if (j2 == "") { 
     alert('saisir le nom du deuxieme joueur'); 
    } 

    if (j2 && j1) { 
     window.location.href = "http://www.google.com"; 
    } 

    e.preventDefault(); 
}); 
+0

我喜歡你說的,但它不工作! – lamloumi

+0

@lamloumi:會發生什麼?你有任何錯誤? – Blender

+0

是的相同的錯誤沒有重定向 – lamloumi

1

要重定向,您只需更改location全局變量:

location = "http://www.google.com" 

你這麼做沒有什麼因爲你通常只是將選擇器或回調傳遞給jQuery函數$(...)(例如$("#something a"))。location是由JavaScript提供的全局變量。

+1

jQuery也可以包裝對象。 – Blender

+0

我更改了「$(location).attr('href',」http://www.google.com「);」通過「location =」http://www.google.com「」但同樣的事情! – lamloumi

+0

做完整的網址:'location =「http://www.google。com /「;' – theabraham

0

與普通的JavaScript

window.location = "http://www.google.com" 

編輯替換您的

$(location).attr('href',"http://www.google.com"); 

好了,我的錯,有一個額外的問題,你是不是返回false時,有是表單的問題,也不是重定向時的問題,因此表單(POST)的deafult操作會打破以前的導航窗口。陽離子

清理代碼位,並更加關注的領域,當你打開網頁,並在未填充的領域之一,剛剛發佈了一個演示在http://fiddle.jshell.net/P3zbb/show/light/

您可以在http://jsfiddle.net/P3zbb/看到代碼的mods

+1

建議兩次,並不能解決問題前者也可以。 –

+0

@Marcos沒有任何變化 – lamloumi

+0

@JanDvorak你是對的!還有一個問題,只是編輯了我的答案,請現在就試試。 –