簡體   English   中英

如何在Ajax調用中保留上下文

[英]How to retain context across an Ajax call

我需要進行Ajax調用並讓響應更新DOM元素的子元素,該元素被單擊以觸發事件。 示例HTML:

<div class="divClass">
  <p class="pClass1">1</p>
  <p class="pClass2">Some text.</p>
</div>
<div class="divClass">
  <p class="pClass1">2</p>
  <p class="pClass2">Some text.</p>
</div>
<div class="divClass">
  <p class="pClass1">3</p>
  <p class="pClass2">Some text.</p>
</div>

示例javascript代碼:

$(document).ready(function(){
    $(".divClass").each(
        function(e) {
            $(this).attr('divValue', $('p.pClass1', this).text());
            $('p.pClass1', this).text('?');

            $(this).click(function(e) {
                e.preventDefault();

                $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: "val=" + $(this).attr('divValue'),
                    success: function(msg) {
                        myData = JSON.parse(msg);
                        $('p.pClass1', this).html(myData.results[0]); // problem exists here
                    }
                });
            });
        }
    );
});

在問題行上“this”指的是Ajax響應對象。 我不知道如何保留上面幾行的“this”上下文,所以我可以用Ajax調用的響應來更新它的內容。

關閉!

$(document).ready(function(){
    $(".divClass").each(
        function(e) {
            $(this).attr('divValue', $('p.pClass1', this).text());
            $('p.pClass1', this).text('?');

            $(this).click(function(e) {
                e.preventDefault();

                // Store 'this' locally so it can be closed
                // by the function scope below
                var self = this;

                $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: "val=" + $(this).attr('divValue'),
                    success: function(msg) {
                        myData = JSON.parse(msg);

                        // Now used your closed variable here
                        $('p.pClass1', self).html(myData.results[0]); // problem exists here
                    }
                });
            });
        }
    );
});
var self = this;
$.ajax({ ..., success: function (msg) { ... $('p.pClass1', self) ... } ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM