El script en línea deja de funcionar después del envío del formulario

I've the following HTML:

    <a id="foo">Click Me</a>

    <form action="" method="post">
        <input type="submit" value="submit">
    </form>

    <script type="text/javascript">

        $(function() {
            $('#foo').click(function() {
                alert('hello');
            });
        });

    </script>

As you can see, "Click me" works fine until I click the submit button (which reloads the page).

How can I prevent this from happening so that "Click me" works as expected even after form submission?

Nota: Here's what's inside my <head>:

<head>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
</head>

Actualizar: Intenté eliminar

<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" /> en la head tag, it works, however this CSS file is an essential part of Jquery Mobile.

preguntado el 05 de mayo de 13 a las 20:05

I don't see how the form reloading the page kills the click event ? -

@rlemon apparently when using Jquery Mobile, it does. -

Anchors should have href atributo. -

This is a jQuery Mobile, href is not needed when working with jQM buttons. -

2 Respuestas

There are few possibilities.

Puedes agregar atributo data-ajax = "falso" to your form. Because of this your form will act as a normal form. Without it jQuery Mobile will handle form submitting and this is something you don t probably want.

<form action="" method="post" data-ajax="false">
    <input type="submit" value="submit">
</form>

Other solution is to change how you bind click event. Instead of your way you should use modern solution like this:

$(document).on('click','#foo',function() {
    alert('hello');
});

One last thing. Unless you know what you are doing don't use this code to bind a click event on DOM ready:

    $(function() {
        $('#foo').click(function() {
            alert('hello');
        });
    });

Unlike pure jQuery, jQuery Mobile uses different logic. This is because when document ready triggers jQuery Mobile page is usually still not fully loaded and enhanced inside a DOM. Because of this jQM developers have created page events. If you want to find more read my other answer about that topic: jQuery Mobile: document ready vs page events

contestado el 23 de mayo de 17 a las 12:05

Puedes cambiar esto:

   <input type="submit" value="submit">

Para:

   <input type="button" value="submit">

Tell me that this is.. :D

contestado el 05 de mayo de 13 a las 20:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.