Jquery, looping over arrays

孤者浪人 提交于 2019-12-13 07:44:23

问题


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() { 
 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.


回答1:


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.




回答2:


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




回答3:


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>


来源:https://stackoverflow.com/questions/5833683/jquery-looping-over-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!