Ver Mensaje Individual
  #5 (permalink)  
Antiguo 25/03/2010, 13:10
Dany_s
 
Fecha de Ingreso: diciembre-2009
Ubicación: Misiones
Mensajes: 867
Antigüedad: 14 años, 5 meses
Puntos: 65
Respuesta: (jQuery) jQuery no me reconoce selectores de div cargados via ajax

jquery no maneja eventos en elementos creados dinamicamento en un futuro con append, prepend, etc y tampoco con ajax. Pero para eso está el evento live.

Esto NO funciona:
Código PHP:
<html>
<
head>
    <
title>Prueba</title>
    <
script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function(){
        
        $('a').click( function (){
            alert ( $(this).text() );
        });
        $('body').append('<a href="#">No funciona</a>')
    });
    </script>
</head>
<body>
    <a href="#">Funciona</a>
</body>
</html> 
Esto SI funciona:
Código HTML:
<html>
<head>
    <title>Prueba</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function(){
        
        $('a').live('click', function (){
            alert ( $(this).text() );
        });
        $('body').append('<a href="#">No funciona</a>')
    });
    </script>
</head>
<body>
    <a href="#">Funciona</a>
</body>
</html> 
El primer ejemplo que no funciona si cambian append antes del evento click va a funcionar

Por ajax si tienen una pagina que se llama pagina.html con un link
Código HTML:
<a href="#">link</a> 
y llaman a esa página y con un evento click NO funciona
Código HTML:
<html>
<head>
    <title>Prueba</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function(){
        $('body').load("pagina.html");
        
        $('a').click( function (){
            alert ( $(this).text() );
        });
        
    });
    </script>
</head>
<body>

</body>
</html> 

Pero esto con evento live SI funciona
Código HTML:
<html>
<head>
    <title>Prueba</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function(){
        $('body').load("pagina.html");
        
        $('a').live('click', function (){
            alert ( $(this).text() );
        });
        
    });
    </script>
</head>
<body>

</body>
</html>