在每个循环上创建数组对象 [英] creating array object on each loop

查看:106
本文介绍了在每个循环上创建数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为ID为#user的每个元素创建一个ddData对象,但是由于某种原因,它仅显示最后一个对象.

I'm trying to create an ddData object for each element with id #user, but for some reason it is just displaying the last object.

var count = $('*#user').length;
ddData = [];
i = 1;
$.each($('*#user'), function () {
    for (i = 1; i <= count; i++) {
        $names = $(this).html();
        ddData = [{
            text: $names,
            value: i++,
            imageSrc: "images/usuari.png"
        }];

        console.log($names);
    }
});

$('#usuarisLlista').ddslick({
    data: ddData,
    width: "200px",
    imagePosition: "left",
    selectText: "Selecciona un usuari"

});

因此console.log(names)输出存在的3个元素(元素的数量可以增加,因此不能为固定的数量):

So the console.log(names) output the 3 elements there are (the number of elements can be increased so it can't be a fixed number):

但是,它仅显示最后一个:

But, it is only displaying the last one:

有人可以告诉我为什么我没有正确执行循环吗?我试图找到解决方案,并且在较旧的文章中发现可以使用push(),但我不明白在代码中将其添加到何处:S

Can anyone tell me why I am not doing the loop properly? I've tried to find the solution, and I've found in older posts I can use push(), but I can not understand where to add it in my code :S

谢谢!

推荐答案

使用push在数组中添加新元素

Use push to add new elements in the array

ddData.push({
    text: $names,
    value: i++,
    imageSrc: "images/usuari.png"
});

何时

ddData = [{
    text: $names,
    value: i++,
    imageSrc: "images/usuari.png"
}];

使用

时,变量将使用分配的值重新初始化.因此,在循环之后,只有最后一个元素会出现在数组中.

is used, the variable will be reinitialized with the value assigned. So, after loop, only the last element will be present in the array.

还有一件事是选择ID为user的元素的选择器不正确.

One more thing is that the selector to select the element with id user is incorrect.

var count = $('*#user').length; // Remove * from this


该代码包含重复的ID. ID应该是唯一的,请使用class而不是id.


The code contains duplicate ids. ID should be unique, use class instead of id.

演示

$(document).ready(function() {

  var ddData = [];
  var i = 0;
  $.each($('.user'), function() {
    var names = $(this).html();
    ddData.push({
      text: names,
      value: i++,
      imageSrc: "images/usuari.png"
    });
    console.log(names);
  });

  $('#userList').ddslick({
    data: ddData,
    width: "200px",
    imagePosition: "left",
    selectText: "Select a user"
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/ddslick/2.0/jquery.ddslick.js"></script>
<table>
  <tr>
    <td class="user">Evelia Molina</td>
    <td class="user">Andy Gon</td>
    <td class="user">Berta Belgrat</td>
  </tr>
</table>
<div id="userList"></div>

这篇关于在每个循环上创建数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆