2011-04-29 80 views
0

我想循環一個數組。該數組將根據您從選擇框中選擇哪個選項而有所不同。我無法弄清楚如何選擇要循環的數組。不工作的位是每個循環內的'arrValues + thisId'。jquery,循環陣列

$('.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++; 
    } 
); 
}); 

任何幫助將是偉大的。

+2

爲什麼不使用多維數組? – Hannes 2011-04-29 14:56:56

回答

0

如果你想在運行時構建的變量名,使用eval

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

只要確保其參數的安全性,尤其是如果它在某種程度上依賴於外部/用戶輸入。在上面的情況下,如果thisId是一個整數,一切都應該沒問題。

+0

Booyah,我喜歡這個網站。謝謝 – twsJames 2011-04-29 15:13:31

0

您可以使用窗口[「foobar」],例如,,但使用Hannes所說的多維數組是最好的方法。

0

那你怎麼能訪問多維數組

<!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>