0

How do i get the href value from a link that is loaded with $.get? My scrip always uses the value that used to be in the div, not the value that was loaded afterwards.

The code:

<html>
<body>
<div id="wrapper">
  <div id="more">
    content
  </div>
  <div class="paglink">
    <a href="/the/url/to/page/1">More</a>
  </div>
</div>
<script>
jQuery(document).ready(function($) {

     $(".paglink a").click(function(e) {
          e.preventDefault();
          $.get($(".paglink a").attr('href'), function(data){ 
            $(data).find("#more").appendTo("#more");
            $(".paglink").html($(data).find(".paglink").html());
          });     
     });

});
</script>
</body>
</html>

Page that gets loaded:

<html>
<body>
<div id="wrapper">
  <div id="more">
    content
  </div>
  <div class="paglink">
    <a href="/the/url/to/page/2">More</a>
  </div>
</div>
</body>
</html>

In short: what do i have to write instead of

$(".paglink a").attr('href')

to get the value from the freshly loaded link?

Bart Rylant
  • 173
  • 1
  • 1
  • 7

1 Answers1

0

Seems that you are dynamically loading elements to your html, that way the new elements have no click event attached to them because you probably attach it on document.Ready()..

jQuery has a "on" API that you could use to attach click events to DOM elements loaded dynamically.

Try this code

$(".paglink").on('click' , 'a', function(e) {
          e.preventDefault();
          $.get($(this).attr('href'), function(data){
              alert(data);
            $(data).find("#more").appendTo("#more");
            $(".paglink").html($(data).find(".paglink").html());
          });   
 });

This code is coorect

$(data).find("#more").appendTo("#more");

You take only the html content that belongs to #more element

Additional information

Silagy
  • 3,053
  • 2
  • 27
  • 39