Jquery / Handlebars.js填充json数组中的select字段

时间:2016-06-25 03:18:22

标签: jquery json handlebars.js

我需要根据json数组“选项”填充选择字段

我的脚本看起来像这样:

var option =  [
    {"mod":"A","values":
        {"Field":"A","Value":"101"}
    },
    {"mod":"B","values:
        {"Field":"B","Value":"102"}},
    {"mod":"C","values"
        {"Field":"C","Value":"99"}
    },
    {"mod":"D","values":    
        {"Field":"D","Value":"96"}
    }];


var theTemplateScript = $('#shoe-template').html(); 
var theTemplate = Handlebars.compile(theTemplateScript); 
$('.shoesNav').append(theTemplate(option));

我的html如下:

<script id="shoe-template" type="x-handlebars-template">
    {{#each option}}
        <option value="{{values.Value}}">
           {{values.Field}}
        </option>
    {{/each}}

</script>
<select class="shoesNav">        
</select>

我没有任何控制台错误,但是字段没有填充,我缺少什么?

JSFiddle HERE

1 个答案:

答案 0 :(得分:1)

您需要使用{{#each option}}循环中的键对数据对象命名空间,在本例中为option。这是一个有效的实施方案:

var namespace = 'option';
var data = {};

data[namespace] = [{
    "mod": "A",
    "values": {
        "Field": "A",
        "Value": "101"
    }
}, {
    "mod": "B",
    "values": {
        "Field": "B",
        "Value": "102"
    }
}, {
    "mod": "C",
    "values": {
        "Field": "C",
        "Value": "99"
    }
}, {
    "mod": "D",
    "values": {
        "Field": "D",
        "Value": "96"
    }
}];

var theTemplateScript = $('#shoe-template').html();
var theTemplate = Handlebars.compile(theTemplateScript);
$('.shoesNav').append(theTemplate(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
<script id="shoe-template" type="x-handlebars-template">
    {{#each option}}
    <option value="{{values.Value}}">
        {{values.Field}}
    </option>
    {{/each}}
</script>
<select class="shoesNav">
</select>
我还更新了你的小提琴:http://jsfiddle.net/cu7n6j95/3/

我希望有所帮助。