0

我的正文部分中有以下 html 元素:

<a class="tog" href="#">Click Me</a> 
<div class="result">
    This is a container div
</div> <br />
<a class="tog" href="#">Click Me</a> 
<div class="result">
    This is a container div
</div>

头部包含以下内容:

.result{
    display: none;
}

我想要做的是,在单击每个链接<a>时,下一个div将切换,同时它将div通过post. 所以我的jQuery代码是:

$(document).ready(function () {
    $(".tog").click(function () {
        if (!$(this).next(".result").data('loaded')) {
            $.post("anotherpage.php", {
                id1: "value1"
            }, function (data) {
                $(this).next(".result").html(data);
                $(this).next(".result").data('loaded', true);
            });
        }
        $(this).next(".result").slideToggle("slow");
        return false;
    });
});

每个链接旁边的每个 div<a>都可以通过上面的代码很好地切换。但是数据不是从另一个页面获取的。如果我从上述代码的每个点中排除 $(this).next ,如下所示:

$(document).ready(function () {
    $(".tog").click(function () {
        if (!$(".result").data('loaded')) {
            $.post("anotherpage.php", {
                id1: "value1"
            }, function (data) {
                $(".result").html(data);
                $(".result").data('loaded', true);
            });
        }
        $(this).next(".result").slideToggle("slow");
        return false;
    });
});

在单击每个链接并post从另一个页面获取数据后,每个 div 都会切换,但是单击任何链接都会同时将数据div一起获取到所有 s。

我的问题是如何修改代码,以便单击每个链接将切换div到该链接旁边并div仅将数据提取到下一个?

4

1 回答 1

0

我相信这里的问题是$(this)在 ajax 包装器中丢失了上下文。因此您需要在 click 函数中存储对原始元素的引用,并在成功函数中调用缓存的对象。

$(".tog").click(function(){
    var $this = $(this); //cached reference

然后以后..

},function(data){   
    //note how we use $this, instead of $(this)
    $this.next(".result").html(data);
    $this.next(".result").data('loaded',true); 
于 2013-03-27T06:51:32.020 回答