所以我们有一个消息系统,有时会有多条消息,并且每条消息在发送者和接收者之间都有不同数量的共同联系人。
当有多个接受的消息时,目前我使用 each
查找类为 .outbox_accepted_row
的所有行,然后使用函数获取成员 ID并进行 API 调用以获取我需要在这些行中显示的一些数据。
例如,第 1 行有 7 个常用联系人,第 2 行有 17 个。但是目前我的代码是如何编写的,最后一个数字 17
会覆盖所有行。
应该如何重写?
// This will find 2 rows on the page, grab the member id's and call
// getNameGameCounts twice:
$(".outbox_accepted_row").each( function( i, el ) {
var elem = $( el );
var member_id = elem.data('member-id');
getNameGameCounts(member_id);
});
function getNameGameCounts(member_id) {
// Here I make the api call with the id to get the counts I need:
WHOAT.networking.getToServerWithAjax(('/api/v1/name_game/play/'+member_id), null, function (response) {
// response comes back
if (response) {
// if the response has contacts
if (response.contacts !== null || undefined) {
// here is the problem
// every row will get overridden with the last count :(
$(".outbox_accepted_row .name_game p").each( function( i, el ) {
var elem = $(el);
elem.html(response.contacts.length);
elem.addClass('open_modal');
});
wireGetNameGame();
}
}
});
};
最佳答案
我认为不要在第二个回调中更改 dom
elem.html(response.contacts.length);
你应该在第一个循环中执行此操作
$(".outbox_accepted_row").each
getNameGameCounts 应该只返回数据,而不是执行另一个 dom 操作,它可能会遇到 aync 问题并返回未定义,您需要像 async.js 一样使用。
还有一件事,您确定要循环 ajax 调用吗?看起来是一个糟糕的设计。
关于javascript - 如何迭代行,获取数据并将其放入行中而不覆盖所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24666641/