javascript
  • jquery
  • arrays
  • json
  • for-loop
  • 2013-05-07 54 views 1 likes 
    1

    我想用数组内的数据动态地创建一个选择框,我试着看一些JSON教程,但仍然有一些麻烦。使用数组动态创建一个选择框

    var clothes = [ 
        Red Dress:"reddress.png", 
        Blue Dress:"bluedress.png", 
        Black Hair Pin:"hairpin.png" 
    ]; 
    
    var select = '<select id="clothing_options">'; 
    for(var i=0;i<clothes.length;i++) 
    { 
        select +='<option value="'+secondPart[i]+'">'+firstPart[i]+'</option>'; 
    } 
    
    $('#select_box_wrapper').append(select+'</select>'); 
    
    $('#clothing_options').change(function() { 
        var image_src = $(this).val(); 
        $('#clothing_image').attr('src','http://www.imagehosting.com/'+image_src); 
    }); 
    

    正如您所看到的代码不完全正常工作,因为它没有被正确写入。如何从第二部分获取数据以及第一部分的选项文本?基本上HTML应该看起来像这样

    <select id="clothing_options"> 
         <option value="reddress.png">Red Dress</option> 
         <option value="bluedress.png">Blue Dress</option> 
         <option value="hairpin.png">Black Hair Pin</option> 
        </select> 
    

    感谢您的任何解释或建议。只是希望这个代码工作,因为我只是在做我自己

    回答

    3

    则可以将阵列更改为JSON对象..

    var clothes = { 
    "Red Dress":"reddress.png", 
    "Blue Dress":"bluedress.png", 
    "Black Hair Pin":"hairpin.png" 
    }; 
    

    然后迭代变得更加容易..

    for(var item in clothes) 
    { 
        $('<option value="'+item+'">'+clothes[item]+'</option>').appendTo('#clothing_options'); 
    } 
    

    这里的HTML:

    <div id="select_box_wrapper"> 
        <select id="clothing_options"></select> 
    </div> 
    

    Demo

    +0

    谢谢你的解释。现在为(衣服里的var item)行可以是任何东西? – EasyBB 2013-05-07 02:50:48

    +0

    是的,var'item'可以被称为任何东西。它表示json对象中的每个项目。 – ZimSystem 2013-05-07 09:28:31

    1

    第一个问题,这些代码的教训:

    var clothes = { 
    Red_Dress:"reddress.png", 
    Blue_Dress:"bluedress.png", 
    Black_Hair_Pin:"hairpin.png" 
    }; 
    

    你不能在标识符空间。

    其次,遍历对象:

    for (var key in clothes) 
    { 
        select +='<option value="'+clothes[key]+'">'+key+'</option>'; 
    } 
    

    当然,这具有示出在选择框“Red_Dress”的不期望的效果。

    var clothes = { 
    "Red Dress":"reddress.png", 
    "Blue Dress":"bluedress.png", 
    "Black Hair Pin":"hairpin.png" 
    }; 
    

    这将修复它。

    +0

    谢谢你他对这一切的解释 – EasyBB 2013-05-07 02:50:03

    相关问题