我知道如何在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;
});
});
“这是错误的”评论的行没有我想要的$(这个)。它似乎包含前一个表达式的结果,而不是我选择的元素(“.pager A”)。
我该怎么做?
奖金问题:Visual Studio抱怨“.get是一个保留字,不应该用作标识符”。究竟是什么问题?
编辑:抱歉,我的意思是<div id="container-1">
,而不是<div class="container-1">
。同上第二个div。
答案 0 :(得分: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;
});
});
答案 1 :(得分: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()
之类的内容