j在 AJAX 中调用函数时查询此指针作用域

jquery this pointer scope when call a function in ajax

本文关键字:查询 指针 作用域 函数 AJAX 调用      更新时间:2023-09-26

我想在通过 xml 文件时从 $.ajax 调用外部函数,但在这种情况下,我对这个指针的作用域感到困惑。

所以在我的 ajax 函数中

function getCustomerInfo (customerID) {
    $.ajax ({
        type: "GET",
        url: "./content/customer_list.xml",
        dataType:"xml",
        success: function (xml) {
            $(xml).find("customer[value=" + customerID + "]").each(function(){
//I want to create a function and call here to achieve the following commented code
//the commented code works fine. I just want to change it to a function because 
//otherwise I have to hard code many similar lines...
// so here is the current function I call:
                addCustomerDetails("timeAdded", "time_added");
// the following code works fine:
                // var timeAdded = $(this).children('time_added').text();
                // var lastUpdate = $(this).children('last_update').text();
                // $("#time_added").html("<p>" + timeAdded + "</p>");
                // $("#last_update").html("<p>" + lastUpdate + "</p>");
            });
        }
    });
}

所以当前的addCustomerDetails函数:

function addCustomerDetails (varName, tagName) {
    window[varName] = $(this).children("time_added");
    $("#"+tagName).html("<p>"+window[varName]+"</p>");
}

所以我需要一个变量名作为参数,所以我使用了 window[varName]。也许这也是一个问题,但我认为addCustomerDetails((中的$(this(似乎也不起作用。

我希望我已经解释清楚了。如果这还不够清楚,请发布任何问题,非常感谢您的帮助!!

function addCustomerDetails (tagName) {
    var tag = $(this).children(tagName).text();
    $("#" + tagName).html("<p>" + tag + "</p>");
}

并像这样称呼它:

addCustomerDetails.call(this, "time_added");
addCustomerDetails.call(this, "last_update");

或者按照这条路,你可以发明一些更方便使用的东西:

$(xml).find("customer[value=" + customerID + "]").each(appendTag('time_added', 'last_update'));

其中appendTag如下所示:

function appendTag() {
    var tags = [].slice.call(arguments);
    return function() {
        for (var i = 0; i < tags.length; i++) {
            var tag = $(this).children(tags[i]).text();
            $("#" + tags[i]).html("<p>" + tag + "</p>");
        }
    };
}

当您调用 getCustomerInfo,假设调用方有权访问 addCustomerDetails,您可以在进行 ajax 调用之前保存对它的引用,然后使用该引用调用 addCustomerDetails,或者在分配的"self"没有访问权限时将其作为调用方传递,例如:

var self = this;
$.ajax(
   ....
   self.addCustomerDetails(...);
);

如果addCustomerDetails不在self的上下文中,另一个选项是:

addCustomerDetails.apply(self, ...)

有关调用和应用之间的区别,您可以查看此SO线程:

电话和申请有什么区别?