开发者

Jquery, looping over arrays

开发者 https://www.devze.com 2023-03-01 19:06 出处:网络
I\'m trying to loop over an array. The array will be different depending on which option you have selected from a selectbox. I can\'t work out how to select which array to loop over. The bit that\'s n

I'm trying to loop over an array. The array will be different depending on which option you have selected from a selectbox. I can't work out how to select which array to loop over. The bit that's not working is 'arrValues+thisId' inside the each loop.

$('.guestLists').change( function(开发者_JAVA百科) { 
 var thisId = $(this).val();
 var myCounter = parseInt(1);

 var arrValues0 = [ "", "", "", "" ];
 var arrValues1 = [ "1", "1", "1", "1" ];   
 var arrValues2 = [ "2", "2", "2", "2" ];
 // Loop over each value in the array.

 $.each(
  arrValues+thisId,
  function( intIndex, objValue ){
  $('#guestListName'+myCounter).attr('value',objValue);
  myCounter++;
  }
 );
});

Any help would be great.


If you want to construct variable name at runtime, use eval:

$.each(
 eval("arrValues"+thisId),
 ...

Just ensure the safety of its parameter, especially if it's somehow dependent on external/user input. In the above case, if thisId is an integer, everything should be fine.


You may use window["foobar"], for example, window["arrValues"+thisId], but using multi-dimensional array like Hannes said is the best way.


Thats how you could access a multi dimensional array

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div id="foo">
        <select class="guestLists">
          <option value="0">0</option>
          <option value="1">1</option>
          <option value="2">2</option>
        </select>
        <div id="stuff"></div>
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
    <script>  
    $('document').ready(function(){
        var Values = Array();
        Values[0] = [ "", "", "", "" ];
        Values[1] = [ "1", "1", "1", "1" ];
        Values[2] = [ "2", "2", "2", "2" ];

        $('.guestLists').change( function() { 
            var thisId = $(this).val();

            $.each(
                Values[thisId],
                function( intIndex, objValue ){
                    $('div#stuff').append(objValue + ', ');
                }
            );
        });
    });

    </script> 
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消