javascript - jquery在ajax中调用函数时this指针作用域

标签 javascript jquery ajax scope this

我想在访问 xml 文件时从 $.ajax 调用外部函数,但在这种情况下我对 this 指针的范围感到困惑。

所以在我的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>");
        }
    };
}

关于javascript - jquery在ajax中调用函数时this指针作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27581128/

相关文章:

javascript eventlistener 立即触发而不是事件触发

javascript - 如何让浏览器检测到哈希更改

javascript - 将值从 json 文件传输到 vue2 谷歌地图标记

javascript - 从被点击的元素image src中放入image src并更新数据

jquery 对话框 zindex 每次打开时都会增加

jquery - 获取时间戳/1000 - Jquery datepicker

javascript - 关于 Parse.com 客户端共享应用程序和 API key

javascript - jquery ajax调用冲突?

javascript - 在 iframe 中加载页面时显示图像

JavaScript - 如何从下拉选择中执行特定查询?