在"myFunction"里面,我有一个each()迭代器,它可以找到某些元素的高度.如何将每个高度值分配给增量生成的变量名称,可在每个循环外部访问?
function myFunction(){
$('#div1, #div2 ... #divN').each(function(index){
/* Increment variable name here */ = $(this).outerHeight();
});
// Also use those variables here
};
Run Code Online (Sandbox Code Playgroud)
谢谢.
使用数组可以更好地解决此任务,并且由于jQuery的内置方法,您可以轻松地将一组元素中的某些值提取到数组中:
var heights = $('#div1, #div2 ... #divN').map(function(){
return $(this).outerHeight();
}).get();
// `heights` is an array and
// heights[0] = height of first element in the tree
// heights[1] = height of second element in the tree
// ...
Run Code Online (Sandbox Code Playgroud)
我必须强调heights数组的顺序不是你将元素放在选择器中的顺序!jQuery将始终将元素重新排序为它们在DOM中的定位方式.
如果您希望高度以某种方式与可以识别元素的东西相关联,则可以使用其中键是元素ID并且值是高度的对象:
var heights = {};
$('#div1, #div2 ... #divN').each(function(){
heights[this.id] = $(this).outerHeight();
});
// `heights` is an object and
// heights['div1'] = height of element with ID div1
// heights['div2'] = height of element with ID div2
// ...
Run Code Online (Sandbox Code Playgroud)