问题描述:

i did this code :

the file index.php

<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>

my problem is in the event click the redirection to "www.google.com" doesn't work.any suggestions:

  1. what is the cause of this error?
  2. how can i correct it?

网友答案:

There's no need to use jQuery to do something that vanilla JavaScript already does:

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

It isn't working probably because you are using a form and that submits before you can redirect. Catch the submit event:

Change your code to this and it will work:

$('#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();
});
网友答案:

To redirect, you simply change the location global variable:

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

What your doing doesn't work because you usually just pass a selector or callback to the jQuery function $(...) (e.g. $("#something a").) location is a global variable provided by JavaScript.

网友答案:

Replace your

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

with a plain Javascript

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

Edit:

Ok, my fault, there was an added problem, you are not returning false when there are problems with the form, nor when you do the redirection, so the deafult action of the form (POST) breaks the previous navigation window.location

Cleaned code a bit and added focus to the fields, when you open the page, and when one of the fields is not filled, just posted a demo at http://fiddle.jshell.net/P3zbb/show/light/

You can see the code mods at http://jsfiddle.net/P3zbb/

相关阅读:
Top