3

我知道如何在 jQuery 中劫持链接,也知道如何找到元素的父元素,但我似乎无法将两者结合起来。我有多个 div,每个 div 都包含一个链接。我想劫持链接并更新父 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>

这是我对 jQuery 的看法:

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

带有“这是错误的”注释的行没有我想要的 $(this)。它似乎包含前一个表达式的结果,而不是我选择的元素(“.pager A”)。

我怎样才能做到这一点?

奖励问题:Visual Studio 抱怨“.get 是保留字,不应用作标识符”。究竟是什么问题?

编辑:对不起,我的意思是<div id="container-1">,不是<div class="container-1">。第 2 分区同上。

4

2 回答 2

4

尝试保存对当前执行上下文的引用,它指向锚点,以便稍后在回调中引用:

$(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;
    });
});
于 2009-10-04T05:38:29.653 回答
0

首先:

    $(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) 。

第二个 - 您的链接的父元素没有id 属性。如果要替换它的内容,请使用 html() 或 text()

于 2009-10-04T05:55:10.030 回答