views:

47

answers:

4

like this

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
</head>
<body>
<div id="test">321</div>
</body>

<script>
$(document).ready(function(){

    $("#test").click(function(){
        $.ajax({
            url:"http://address/",
            type:"post",
            data:{id:"123"},
            success: function(r)
            {
                $("#test").after(r); // it will return <div id="test2">123</div>
            }
        });
        return false;
    });

    $("#test2").click(function(){
        alert('123');
        return false;
    });

});
</script>
</html>

first click #test and insert #test2 then i click #test2, it can't to get click event, help me, what's problem

+2  A: 

You'll want to use live for this, since the element with the id test2 isn't in the DOM yet.

$('#test2').live('click', function() {
    alert('123');
    return false;
});
Jacob Relkin
+1  A: 

use :

$("#test2").live('click', function(){
    alert('123');
    return false;
});

(sorry double post)

darma
+2  A: 

you can also do this

$(document).ready(function(){

    $("#test").click(function(){
        $.ajax({
            url:"http://address/",
            type:"post",
            data:{id:"123"},
            success: function(r)
            {
                $("#test").after(r); // it will return <div id="test2">123</div>
                $("#test2").click(function(){
                    alert('123');
                    return false;
                });
            }
        });
        return false;
    });
});

add the event after you insert the DOM element

rob waminal
A: 
$(document).ready(function(){

    var fn = function(ev) {
                ev.stopPropagation(); //optional
                alert('123');
                return false;
             };

    $("#test").click(function(){
        $.ajax({
            url:"http://address/",
            type:"post",
            data:{id:"123"},
            success: function(r)
            {
                $("#test").after( $(r).bind('click', fn) );
            }
        });
        return false;
    });
});
andres descalzo