jQuery jquery从函数返回?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10262356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:02:48  来源:igfitidea点击:

jquery return from function?

jqueryfunctionreturn

提问by Digital Brent

I'm trying to understand the right way to return values in jquery from a function. I've checked the API as well as other questions here and I can't find the correct way to do this. All I want is a simple variable to be returned so I can set it as a global variable. Here's what I got:

我试图了解从函数返回 jquery 值的正确方法。我在这里检查了 API 以及其他问题,但找不到正确的方法来执行此操作。我想要的只是一个要返回的简单变量,以便我可以将其设置为全局变量。这是我得到的:

var a = 0, b, c;
var imgArr = [];

  $(document).ready(function() { //populates array with images

        var smooth = popArr();
        alert(smooth);
  }

 function popArr(){
        $("#thumb_slider").children().each(function(index, element) {
            var newImg = $("<img />").attr({
                src: this.src,
                alt: 'space'
            }).addClass(index == 0 ? "left_slot" : (index == 1 ? "middle_slot" : "right_slot"));
            imgArr.push(newImg);
          return imgArr;               // This comes back as undefined.

        });
    }

My question is why is it returning undefined? Am I even supposed to use "return" in Jquery?

我的问题是为什么它返回未定义?我什至应该在 Jquery 中使用“返回”吗?

回答by ThiefMaster

You try to return something from the .eachcallback. The only useful return value of this function is falseto cancel the "loop" early.

您尝试从.each回调中返回一些内容。此函数唯一有用的返回值是false提前取消“循环”。

Simply move your return statement after the });and everything should work fine.

只需在 之后移动您的 return 语句});,一切都应该正常工作。

You can also avoid the global variable - you return the array so there's no need to make it global:

您还可以避免使用全局变量 - 您返回数组,因此无需将其设为全局:

function popArr() {
    var imgArr = [];
    $("#thumb_slider").children().each(function (index, element) {
        var newImg = $("<img />").attr({
            src: this.src,
            alt: 'space'
        }).addClass(index == 0 ? "left_slot" : (index == 1 ? "middle_slot" : "right_slot"));
        imgArr.push(newImg);
    });
    return imgArr;
}

回答by mindandmedia

the method popArr()is not returning anything. instead, it is calling .each()

该方法popArr()不返回任何内容。相反,它正在调用.each()

since it is a global variable, just pushing elements into it will be enough.

因为它是一个全局变量,只需将元素推入其中就足够了。