jQuery-- 从 json 中填充选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16442422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:09:07  来源:igfitidea点击:

jQuery-- Populate select from json

jquery

提问by Doc Holiday

I have a map in my java sevlet and converting it to a json format that works right.

我的 java sevlet 中有一张地图,并将其转换为正常工作的 json 格式。

When I do this function below it creates a drop down, but it puts every character as an option?? This is what I got:

当我在下面执行此功能时,它会创建一个下拉列表,但它将每个字符都作为选项?这是我得到的:

$(document).ready(function(){
    var temp= '${temp}';
    //alert(options);
    var $select = $('#down');                        
    $select.find('option').remove();                          
    $.each(temp, function(key, value) {              
        $('<option>').val(key).text(value).appendTo($select);     
    });
});

map content in JSON format

JSON 格式的地图内容

{"1" : "string","2" : "string"}

回答by webrama.pl

I would do something like this:

我会做这样的事情:

$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

JSON structure would be appreciated. At first you can experiment with find('element')- it depends on JSON.

JSON 结构将不胜感激。起初你可以试验find('element')- 这取决于 JSON。

回答by cjrigdon

Only change the DOM once...

只更改一次 DOM...

var listitems = '';
$.each(temp, function(key, value){
    listitems += '<option value=' + key + '>' + value + '</option>';
});
$select.append(listitems);

回答by NullPointerException

fiddle

小提琴

var $select = $('#down'); 
$select.find('option').remove();  
$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

回答by florex

A solution is to create your own jquery plugin that take the json map and populate the select with it.

一种解决方案是创建您自己的 jquery 插件,该插件采用 json 映射并使用它填充选择。

(function($) {     
     $.fn.fillValues = function(options) {
         var settings = $.extend({
             datas : null, 
             complete : null,
         }, options);

         this.each( function(){
            var datas = settings.datas;
            if(datas !=null) {
                $(this).empty();
                for(var key in datas){
                    $(this).append('<option value="'+key+'"+>'+datas[key]+'</option>');
                }
            }
            if($.isFunction(settings.complete)){
                settings.complete.call(this);
            }
        });

    }

}(jQuery));

You can call it by doing this :

你可以通过这样做来调用它:

$("#select").fillValues({datas:your_map,});

The advantages is that anywhere you will face the same problem you just call

优点是在任何地方你都会遇到同样的问题,你只是打电话

 $("....").fillValues({datas:your_map,});

Et voila !

等等!

You can add functions in your plugin as you like

您可以根据需要在插件中添加功能

回答by Irfan Ashraf

$(JSON.parse(response)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#selectorId');

回答by LameCoder

I just used the javascript console in Chrome to do this. I replaced some of your stuff with placeholders.

我只是在 Chrome 中使用了 javascript 控制台来做到这一点。我用占位符替换了你的一些东西。

var temp= ['one', 'two', 'three']; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');                        
$select.find('option').remove();                          
$.each(temp, function(key, value) {              
    $('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());

Output:

输出:

<option value="0">one</option><option value="1">two</option><option value="2">three</option>

<option value="0">一个</option><option value="1">两个</option><option value="2">三个</option>

However it looks like your json is probably actually a string because the following will end up doing what you describe. So make your JSON actual JSON not a string.

但是,看起来您的 json 可能实际上是一个字符串,因为以下内容最终会执行您所描述的操作。所以让你的 JSON 实际 JSON 不是字符串。

var temp= "['one', 'two', 'three']"; //'${temp}';
//alert(options);
var $select = $('<select>'); //$('#down');                        
$select.find('option').remove();                          
$.each(temp, function(key, value) {              
    $('<option>').val(key).text(value).appendTo($select);
});
console.log($select.html());

回答by David Fawzy

That work fine in Ajax call back to update select from JSON object

这在 Ajax 回调中工作正常以更新来自 JSON 对象的选择

function UpdateList() {
    var lsUrl = '@Url.Action("Action", "Controller")';

    $.get(lsUrl, function (opdata) {

        $.each(opdata, function (key, value) {
            $('#myselect').append('<option value=' + key + '>' + value + '</option>');
        });
    });
}

回答by molabss

I believe this can help you:

我相信这可以帮助您:

$(document).ready(function(){
    var temp = {someKey:"temp value", otherKey:"other value", fooKey:"some value"};
    for (var key in temp) {
        alert('<option value=' + key + '>' + temp[key] + '</option>');
    }
});