首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jquery如何使每个函数最终都能调用更新?

jquery如何使每个函数最终都能调用更新?
EN

Stack Overflow用户
提问于 2012-04-19 21:33:51
回答 2查看 220关注 0票数 0

我有一个循环遍历所有'li‘元素并收集数据的函数。同时,我将所有的数据都推入数组。一旦所有的'li‘循环完成,我需要用更新的数据调用一个函数一次?

我现在的代码是这样的:但它调用了我的函数的3倍,因为它得到了3倍的条件。函数运行良好,我调用函数是错误的,任何好的建议使它在完成所有循环后调用一次。

代码语言:javascript
运行
复制
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..
            }
        })

    })

});

提前谢谢。

EN

回答 2

Stack Overflow用户

发布于 2012-04-19 21:42:42

只需将函数调用移出内部.each循环即可:

代码语言:javascript
运行
复制
    $(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
EN

Stack Overflow用户

发布于 2012-04-19 21:41:46

您可以在each之后使用generatePieURL,因为jQuery each是同步的。

所以:

代码语言:javascript
运行
复制
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(...)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10229218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档