views:

507

answers:

2

I know how to hijack a link in jQuery, and I know how to find an element's parent, but I can't seem to combine the two. I have multiple divs, each of which contains a link. I want to hijack the link and update the parent div's content.

<div class="container-1">
  <a href="/foo.html">Add content</a>
</div>
 <div class="container-2">
  <a href="/bar.html">Add content</a>
</div>

Here's what I have with jQuery:

$(function() {
    $(".pager A").live("click",
    function() {
        $.get($(this).attr("href"),
        function(response) {
            $(this).parent().attr("id").replaceWith(response); // This is wrong
        });
        return false;
    });
});

The line with the "This is wrong" comment doesn't have what I want for $(this). It appears to contain the result from the previous expression, not the element I selected (".pager A").

How can I do this?

Bonus question: Visual Studio complains that ".get is a reserved word and should not be used as an identifier". What exactly is the problem?

EDIT: Sorry, I meant <div id="container-1">, not <div class="container-1">. Ditto for the 2nd div.

+4  A: 

Try saving the reference to the current execution context where it points to the anchor to refer to later in the callback:

$(function() {
    $(".pager A").live("click",
    function() {
        var el = this;
        $.get($(el).attr("href"),
        function(response) {
            $(el).parent().html( response ); // is this what you want? .attr('id') would return a string and you can't call jQuery methods on a string.
        });
        return false;
    });
});
meder
updated with potential code that you want
meder
Many thanks. I think your response was first.
Slack
+1  A: 

First of all:

    $(function() {
      $(".pager A").live("click",
        function() {
          var $link = $(this);
            $.get($(this).attr("href"),
            function(response) {
              $link.parent().attr("id").replaceWith(response); // This is wrong
            });
          return false;
        });
    });

You shouldn't use $(this) in callback function.

And the second - your link's parent element doesn't have id attribute. If you want to replace it's content use something like html() or text()

Andrew Dashin