首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jquery -从函数返回值

jquery -从函数返回值
EN

Stack Overflow用户
提问于 2011-05-16 15:46:15
回答 7查看 34.6K关注 0票数 0

假设我具有以下功能:

代码语言:javascript
复制
function checkPanes() {
    activePane = '';
    var panels = $("#slider .box .panel");

    panels.each(function() {

    //find the one in visible state.
    if ($(this).is(":visible")) {
    activePane = $(this).index()+1;
    console.log(activePane);
    }

    });
} //END checkPanes();

理想情况下,我希望在其他地方(很可能是从另一个函数)调用此函数的,并检索当前输出到控制台的值。

(例如.)

代码语言:javascript
复制
function exampleCase() {
    checkPanes(); //evidently, does not return anything. 
    //Ideally, I want the numerical value, being output to console in above function.
}  

提前感谢!所有的建议/意见都非常感谢。

干杯

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-05-16 15:52:49

忘记那些说return activePane的人吧,因为他们没有看到它在jQuery each循环中。不起作用。

我建议重组你的选择器。您应该使用的选择器是:$("#slider .box .panel:visible")。这将完全切断您的每个循环。例如,您可以按照以下方式重构代码:

代码语言:javascript
复制
function checkPanes() {
    return $("#slider .box .panel:visible").index();
}

function exampleCase() {
    var visiblePane = checkPanes();

    // ... do something with the index
}

我建议只使用线上的选择器,而不是做一个新的功能,但这是一个口味的问题,特别是如果你必须选择相同的东西在多个地方。

票数 2
EN

Stack Overflow用户

发布于 2011-05-16 15:48:20

刚刚注意到了循环;看起来您可能希望返回的是所有活动面板的数组(因为理论上可能有多个面板)。

代码语言:javascript
复制
function checkPanes() {
    activePanes = [];
    var panels = $("#slider .box .panel");

    panels.each(function() {

    //find the one in visible state.
    if ($(this).is(":visible")) {
    activePane.push($(this).index()+1);
    console.log(activePane);
    }

    });
    return activePanes;
} 

如果您知道只有一个active,您可以回到原来的方法,只需在return activePane之后添加console.log

票数 4
EN

Stack Overflow用户

发布于 2011-05-16 15:49:05

只需将控制台行切换到返回语句:

代码语言:javascript
复制
function checkPanes() {
    activePane = '';
    var panels = $("#slider .box .panel");

    panels.each(function() {

    //find the one in visible state.
    if ($(this).is(":visible")) {
        activePane = $(this).index()+1;
        return activePane; // Return the value and leave the function
    }

    });
} //END checkPanes();

打电话:

代码语言:javascript
复制
function exampleCase() {
    var thepane = checkPanes(); //evidently, does not return anything. 
    // ...
}  
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6019859

复制
相关文章

相似问题

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