开发者

JQuery: can't re-update links (I'm new to JQuery)

I'm new to Jquery and I'm getting crazy to reupdate in ajax a code containing urls!! It works the first time, but the link does not work any longer after ajax response rewrites html.

Please, find below my code.

First the HTML markup (View)

<head>  
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript">  
  $(document).ready(function() { 
    $("a[class=unselected_quid], a[class=quid_selected]").click(function(){
        var url = $(this).attr("name");
        alert(url);
        $.ajax({
            url: "index.php", 
            type: "POST",  
            data: url,
            da开发者_Go百科taType: "html",
            success: function(msg) {    
                $("#result").html(msg);  
            },
            error: function(){
                alert("error!!!");
            } 
        });
    });
  });
</script>  
</head> 

<?php // set url strings in php
  $url = "component=Training&ctrl=JQueryTraining&task=ajaxLinkResponse&data=1";
  $url2 = "component=Training&ctrl=JQueryTraining&task=ajaxLinkResponse&data=2";
?>

<body>  
  <div id="result"><br>
    <a name='<?echo $url?>' href='javascript:void(0)' title='uno' class='selected_quid'>link a</a> <br>
    <a name='<?echo $url2?>' href='javascript:void(0)' title='due' class='unselected_quid'>link b</a><br>
  </div>  
</body>

Then the PHP (Controller)

public function ajaxLinkResponse(){
  $url = "component=Training&ctrl=JQueryTraining&task=ajaxLinkResponse&data=1";
  $url2 = "component=Training&ctrl=JQueryTraining&task=ajaxLinkResponse&data=2";

  $code = "<a name='{<?$url?>}' href='javascript:void(0)' title='uno' class='selected_quid'>link a</a> 
  <a name='{<?$url2?>}' href='javascript:void(0)' title='due' class='unselected_quid'>link b</a>";  

  echo($code);
}


You need to use .live() or .delegate() instead of .click() as you are making new DOM elements in your AJAX call and .click() does not cater for DOM element creation.
i.e.

$("a[class=unselected_quid], a[class=quid_selected]").live('click',function(e){
e.preventDefault();
// rest of code

or

$(aWrapper).delegate('a[class=unselected_quid], a[class=quid_selected]','click',function(e){
e.preventDefault();
// rest of code

You may ask 'What's the difference?' well this should help. Basically delegate is faster, will not crash with heavy DOM traversals, and you can supply a context (this is a big feature).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜