JQuery: grab a link and find its parent

I know how to capture a link in jQuery, and I know how to find the parent element, but I cannot combine the two. I have several divs, each of which contains a link. I want to grab the link and update the parent content of the div.

<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 is 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 comment "This is wrong" does not contain what I want for $ (this). It appears to contain the result from the previous expression, not the selected item (".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 is the problem?

EDIT: Sorry, I meant <div id="container-1">, not <div class="container-1">. The same goes for the second div.

+3
2

, , :

$(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;
    });
});
+4

:

    $(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;
        });
    });

$(this) .

- link id. , - html() text()

0

Source: https://habr.com/ru/post/1719201/


All Articles