Javascript return 每个函数的变量
Javascript return variables from each function
使用 each 遍历子元素。
var divHeights = [];
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
alert(divHeights); // fails
如何 return divHeights
变量?
我试过了
var hts = ('#parent').children('div').each(function () { ...
但显然那是行不通的。
您可以使用 .map()
以更好的方式做到这一点,例如:-
var divHeights = $('#parent').children('div').map(function () {
return this.clientHeight || 0;
}).get();
你可以把它变成这样的函数:
function getHeights() {
return $('#parent div').map(function() {
return this.clientHeight;
});
}
然后你可以在任何你喜欢的地方调用函数来获取数组内容。
divHeights
变量始终可用。您可以随时将其分配给变量:
var hts = divHeights;
这只是对数组的另一个引用,因此您可以在创建数组后的任何时候执行此操作,甚至在您将任何值放入其中之前:
var divHeights = [];
var hts = divHeights;
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
当你想使用结果时,你当然可以只使用变量 divHeights
而不是变量 hts
,或者只使用变量 hts
而不是 divHeights
从头开始。
使用 each 遍历子元素。
var divHeights = [];
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
alert(divHeights); // fails
如何 return divHeights
变量?
我试过了
var hts = ('#parent').children('div').each(function () { ...
但显然那是行不通的。
您可以使用 .map()
以更好的方式做到这一点,例如:-
var divHeights = $('#parent').children('div').map(function () {
return this.clientHeight || 0;
}).get();
你可以把它变成这样的函数:
function getHeights() {
return $('#parent div').map(function() {
return this.clientHeight;
});
}
然后你可以在任何你喜欢的地方调用函数来获取数组内容。
divHeights
变量始终可用。您可以随时将其分配给变量:
var hts = divHeights;
这只是对数组的另一个引用,因此您可以在创建数组后的任何时候执行此操作,甚至在您将任何值放入其中之前:
var divHeights = [];
var hts = divHeights;
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
当你想使用结果时,你当然可以只使用变量 divHeights
而不是变量 hts
,或者只使用变量 hts
而不是 divHeights
从头开始。