jQuery的循环动态值 [英] jQuery for loop dynamic value

查看:127
本文介绍了jQuery的循环动态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(var i = 0; i< dataElements; ++ i){
d = document.createElement('div');
$(d).addClass('overviewbit')
.appendTo('。overview')
.click(function(){$ b $ id = i;
});





$ b

每个Div都将id设置为循环的最高值,但我应该是确切的价值,我得到时创建。所以第一个div应该设置为1,第二个div应该设置为2,依此类推。我希望你明白我的问题,并可以帮助我找到一个解决方案。 解决方案

这是一个常见的问题。当你创建点击处理程序时,它将 id 设置为 i - 变量,而不是值 i 当时正在存储。



for 循环在单击任何DIV之前完成,因此 i 等于所有click处理程序的循环中的最终值,结果所有的 id s被设置为相同的值。

使用jQuery,你可以解决这个问题通过使用 .data()存储:

  for(var i = 0; i< dataElements; ++ i){
d = document.createElement('div');
$ .ddClass('overviewbit')
.appendTo('。overview')
.data('val',i)
.click(function() {
id = $(this).data('val');
});





$ b

然而,要做到正确的方式,你可以使用

  for (var i = 0; i< dataElements; ++ i){
d = document.createElement('div');
$ .ddClass('overviewbit')
.appendTo('。overview')
.data('val',i)
.click((function( j){
return function(){id = j;}
})(i));
}


Ive got a problem with the following loop:

for (var i = 0; i < dataElements; ++i){
  d=document.createElement('div');
  $(d).addClass('overviewbit')
  .appendTo('.overview')
  .click(function(){
    id = i;
  });
}

Every Div sets id to the highest value of the loop but i should be the exact value i gets when its created. So the first div should set it to 1, the second div should set it to 2 and so on. i hope you understand my problem and could help me to find a solution.

This a common problem. When you create the click handler, it's setting id to i -- the variable, not the value i was storing at the time.

The for loop is completing before any of the DIVs are clicked, so i is equal to the final value from the loop for all the click handlers, and as a result all the ids are set to the same value.

With jQuery you can solve this problem by using .data() storage:

for (var i=0; i<dataElements; ++i){
    d=document.createElement('div');
    $(d).addClass('overviewbit')
        .appendTo('.overview')
        .data('val',i)
        .click(function(){
                id = $(this).data('val'); 
            });
}

However, to do things the "proper" way you would use a JavaScript closure:

for (var i=0; i<dataElements; ++i){
    d=document.createElement('div');
    $(d).addClass('overviewbit')
        .appendTo('.overview')
        .data('val',i)
        .click((function(j){
                return function() { id = j; }
            })(i));
}

这篇关于jQuery的循环动态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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