我有一个循环遍历所有'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..
}
})
})
});
提前谢谢。
发布于 2012-04-19 21:42:42
只需将函数调用移出内部.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);
发布于 2012-04-19 21:41:46
您可以在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(...)
https://stackoverflow.com/questions/10229218
复制相似问题