gpt4 book ai didi

javascript - 在ajax中调用函数时jquery这个指针范围

转载 作者:行者123 更新时间:2023-11-29 21:53:44 25 4
gpt4 key购买 nike

我想在通过 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>");
}
};
}

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com