简体   繁体   English

在jQuery中使用array.push()内部的变量

[英]Using variable inside array.push() in jquery

I have a for loop in my jquery script 我的jquery脚本中有一个for循环

var images[];
for(i=0;i<$('#imageHolder div').length;i++)
{
    images.push($('#imageHolder div:eq( i )').attr('alt'));
    console.log($('#imageHolder div:eq(i )').attr('alt'));
}

I am not able to add the elements to the array and the console.log says undefined in the console. 我无法将元素添加到数组,console.log在控制台中未定义。 What is my possible error and how that can be corrected? 我可能出现的错误是什么?如何纠正?

jQuery has useful method for this task, called $.fn.map : jQuery为此任务提供了有用的方法,称为$.fn.map

var images = $('#imageHolder div').map(function() {
    return $(this).attr('alt');
}).get();

Will produce an array of images alt attributes. 将产生图像的alt属性数组。

You have a typo: 您有错字:

images.push($('#imageHolder div:eq(' + i + ')').attr('alt')); 
                 you need to concat i ^^^^

By the way, don't select your element every time in the for 顺便说一句,不要每次都在for选择您的元素

var divs = $('#imageHolder div');
for(i=0; i < divs.length; i++)

i is a variable so need to use concatenation i是一个变量,所以需要使用串联

$('#imageHolder div:eq('+  i + ')').attr('alt')

A more efficient way is to use .map(), in your case you are evaluating the selector many times which is not a optimal way 一种更有效的方法是使用.map(),在这种情况下,您要对选择器进行多次评估,这不是最佳方法

var images = $('#imageHolder div').map(function () {
    return $(this).attr('alt')
}).get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM