【问题标题】:jQuery select (Dropdown) populate from arrayjQuery 选择(下拉)从数组中填充
【发布时间】:2014-06-14 02:00:17
【问题描述】:

我目前在这里工作..

$(document).ready(function() {
   $("#image").change(function() {
     $("#imagePreview").empty();
        $("#imagePreview").append("<img src=\"" + $("#image").val()  + "\" />");
   });
 });


<select name="image" id="image" class="inputbox" size="1">
   <option value="imageall.jpg" selected> - All - </option>
   <option value="image1.jpg">image1.jpg</option>
   <option value="image2.jpg">image2.jpg</option>
   <option value="image3.jpg">image3.jpg</option>
</select>

<div id="imagePreview">
</div>

来自上一个问题:

Previous Question

我想知道如何改为从 jQuery 数组填充?

我怎么能这样做?所以基本上是数组中的值和名称

这是我将在 Fiddle 中使用的示例 Example Working

【问题讨论】:

标签: javascript jquery html arrays


【解决方案1】:
function populateSelect(el, items) {
    el.options.length = 0;
    if (items.length > 0)
        el.options[0] = new Option('please select', '');
    $.each(items, function () {
        el.options[el.options.length] = new Option(this.name, this.value);
    });
}

如此处所示: Using javascript and jquery, to populate related select boxes with array structure

【讨论】:

    【解决方案2】:

    您可能希望以这种方式从 JSON 数组中检索名称和值。

    var image_maps = {image1: "image1.jpg", image2: "image2.jpg"};
    $.each(image_maps , function(name, value) {
        alert("name: " + name + " value: " + value);
    });
    

    【讨论】:

    • 请在代码中附上解释性的 cmets。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2014-01-19
    • 2021-09-18
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2011-03-30
    相关资源
    最近更新 更多