开发者

how to redeclare function for particular elements after jquery.ajax responsing?

First please forgive my poor English . My Problem is that how can i re-declare some function for particular elements after responsing from jquery.ajax ?

Here is my code for html :

<a href="#"><img class='alrun' src="images/pic0001.png" width="97" height="97" /></a>

Her开发者_如何学Goe is my code for jquery to bind the click function :

$(document).ready(function() {
  $("img.alrun").bind("click", function(){
  var aaa = ($(this).attr("src") === "images/pic0001.png")? "images/pic0002.png":"images/pic0001.png";
  $(this).attr("src", aaa);
});

Everything works fine and well , the picture will swap when i click the image , however when i using the jquery.ajax from php script to create new DOM elements just like above code of HTML,the "new image" could not be swapped anymore ,

here is my code for more_race.php:

<?echo "<a href='#'><img class='alrun' src='images/pic0001.png' width='97' height='97' /></a>";

?>

here is my jquery code for ajax :

$("a.more_race").click(function(){
    $.ajax({
    type: "POST",
    url: "more_race.php",
    cache: false,
    success: function(html){
    $("div#new_image").html(html);
    }
    });
});

I think all my problem is that i dont know how to re-declare the function for new elements created by jquery , i hope that any one can give me some example to solve my easy problem.

Thsnk a lot!


You need to use the jQuery .live() keyword for any control you add using jQuery or JavaScript.

So

$("img.alrun").live("click", function(){
  // your code here
});

and

$("a.more_race").live....


You should be using .live instead of .click as it will continually listen to elements being added dynamically to the DOM.

$("a.more_race").live('click', function(){
    $.ajax({
    type: "POST",
    url: "more_race.php",
    cache: false,
    success: function(html){
    $("div#new_image").html(html);
    }
    });
});

It works that way, because when you bind a click event, JavaScript will take a "snapshot" of the current DOM and work with that, new elements being added will not count. .live however listens to new elements creation and applies the click binding to them as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜