我有一个函数来遍历所有'li'元素并收集数据。 此外,我正在将所有数据推送到数组。 一旦所有"li"循环完成,我需要使用更新的数据调用一次函数?
我目前的代码是这样的: 但它调用了 3 倍我的函数,因为它得到了 3 倍的条件。 该函数工作正常,我调用该函数是错误的,任何好的建议都是在完成所有循环后调用一次。
var pieIndex = [];
$('button.pieDraw', $(accordionBox)).live('click', function () { //done button
var uls = $(accordionSec.accorGeography).find('ul');
$.each(uls, function (i, val) {
pieIndex = []; //i am clearing the array each time to get new value
var currentLI = $(val).find('li');
$(currentLI).each(function () {
if ($(this).hasClass('c_on')) { // this is finding the class 3 times. it's fine
var functionName = pieFunction[$(this).parent().attr('title') + 'Pie'].fun;
pieIndex.push($(this).attr('data-index')); // at the last i am getting 1,2,3 it's correct.
generatePieURL(functionName, curQI, crrentMonth, currentYear, pieIndex);
//it is calling 3 times. i need only one time to call..
}
})
})
});
提前谢谢。
只需将函数调用从内部.each
循环中取出:
$(currentLI).each(function () {
if ($(this).hasClass('c_on')) {
var functionName = pieFunction[$(this).parent().attr('title') + 'Pie'].fun;
pieIndex.push($(this).attr('data-index'));
}
})
generatePieURL(functionName, curQI, crrentMonth, currentYear, pieIndex);
你可以在
each
之后使用generatePieURL
,因为jQuery each
是同步的。
所以:
var functionName; // will be filled in the following loop (only if the output will be the same at each loop
$(currentLI).each(function(){
if($(this).hasClass('c_on'))
...
return false; // to stop the each, if not needed anymore
})
if pieIndex.length > 0
generatePieUrl(...)