jquery函数返回? [英] jquery return from function?
问题描述
我试图理解从函数返回jquery中的值的正确方法。我已经检查了API以及其他问题,我无法找到正确的方法来做到这一点。我只想要一个简单的变量来返回,所以我可以将它设置为一个全局变量。这是我得到的:
var a = 0,b,c;
var imgArr = [];
$ b $(文档).ready(函数(){//用数组填充数组
var smooth = popArr();
alert(smooth);
函数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; //返回未定义状态
)};
}
我的问题是为什么它返回undefined?应该在Jquery中使用return?
您试图从 .each
callback。这个函数唯一有用的返回值是 false
,以便尽早取消循环。
Si mply将你的return语句移到
});
之后,并且一切都应该正常。你也可以避免全局变量 - 你返回数组,因此不需要使它成为全局变量: 函数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);
});
返回imgArr;
}
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:
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?
You try to return something from the .each
callback. The only useful return value of this function is false
to cancel the "loop" early.
Simply move your return statement after the });
and everything should work fine.
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;
}
这篇关于jquery函数返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!