我有一个循环遍历所有'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..
}
})
})
});
提前感谢。
答案 0 :(得分:1)
从内部.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);
答案 1 :(得分:0)
您可以在generatePieURL
之后使用each
,因为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(...)