点击与一个for循环事件通过一个数组只给我的最后一个项目? [英] click event with a for loop through an array only gives me the last item?

查看:181
本文介绍了点击与一个for循环事件通过一个数组只给我的最后一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

var bar = [];

我有一个for循环遍历数组会:

I have a for loop going through the array:

            for (var i = 0; i <= 3; i++) {
                $(".left-lg").find(".name").html(bar[i].name);
            }

我试图与阵列中的内容,以取代DIV.name的内容,它的工作原理,但只给我的阵列中的最后一个。我看了,就用JavaScript循环将在年底click事件,所以这就是为什么。

I am trying to replace the content of the DIV.name with the content in the array, it works but only gives me the last one in the array. I read, on a click event with javascript the loop will be at the end, so that is why.

什么办法如何解决这一所以它会经过整个循环,而不是只给最后一个?

Any way how to correct this so it will go through the entire loop and not just give the last one?

推荐答案

这是因为你总是设置的HTML内容的所有的匹配元素。名称。尝试使用首页参数提供给每()而不是:

That's because you're always setting the HTML content of all the elements matching .name. Try using the index argument supplied to each() instead:

$(".left-lg .name").each(function(index) {
    $(this).html(bar[index].name);
});

这篇关于点击与一个for循环事件通过一个数组只给我的最后一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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