![](/img/trans.png)
[英]How can I iterate over a list of objects in Handlebars.js with two if conditions?
[英]Using Handlebars.js to iterate over a list of names
我有一個 Bootstrap select 下拉菜單,我正在嘗試使用 Handlebars JS 將所需的選項 output 添加到我的選擇中,但它們沒有出現。 我在這里閱讀了一些示例,所以不確定是什么阻止了我的代碼正確呈現,任何指針將不勝感激。
HTML:
<select class="custom-select" id="inputGroupSelect01" onChange="takeSelectedSourceValue(this);">
<option id="source-language" value="" selected disabled>Auto</option>
<div id="myForm"></div>
<script type="text/handlebar-template" id="selectPersonTemplate">
{{#each people}}
<option value="{{valueLang}}">{{htmlLang}}</option>
{{/each}}
</select>
</script>
<script src="https://twitter.github.io/typeahead.js/js/handlebars.js"></script>
記者:
$(function () {
// Define an array of people.
var people = [
{ valueLang: 'DE', htmlLang: 'DE' },
{ valueLang: 'FR', htmlLang: 'FR' },
{ valueLang: 'IT', htmlLang: 'IT' },
{ valueLang: 'ES', htmlLang: 'ES' },
{ valueLang: 'SV', htmlLang: 'SV' },
{ valueLang: 'DA', htmlLang: 'DA' }
];
// Get the text for the Handlebars template from the script element.
var templateText = $("#selectPersonTemplate").html();
// Compile the Handlebars template.
var selectPersonTemplate = Handlebars.compile(templateText);
// Evaluate the template with an array of people.
var html = selectPersonTemplate({ people: people });
// Take the HTML that was created with the Handlebars template and
// set the HTML in the myForm div element.
$("#myForm").html(html);
});
您的 HTML 有一些問題。
首先,您的結束標記 select </select>
位於您的模板腳本標記內。
HTML 解析器會忽略腳本標記中的內容,因為您已將腳本定義為type="text/handlebar-template"
。 因此,解析器看不到結束標記 select。
其次, <div>
元素不是 select, <select>
元素的有效子元素。
我不確定是否所有瀏覽器都以相同的方式處理這個無效標簽,但我正在使用 Chrome 進行嘗試,Chrome 似乎在呈現時完全忽略了<div id="myForm"></div>
。 因此,沒有要添加模板html
生成的 html 的html
值應附加到<select>
。
為了清楚起見,我建議從<select>
中取出模板<script>
標記。 這將使 HTML 更易於閱讀,並將<select>
菜單與模板清楚地分開。
<select class="custom-select" id="inputGroupSelect01" onChange="takeSelectedSourceValue(this);">
<option id="source-language" value="" selected disabled>Auto</option>
</select>
<script type="text/handlebar-template" id="selectPersonTemplate">
{{#each people}}
<option value="{{valueLang}}">{{htmlLang}}</option>
{{/each}}
</script>
接下來,我們要確保append html
到我們的#inputGroupSelect01
元素。
// append the HTML to the #inputGroupSelect01 select element.
$("#inputGroupSelect01").append(html);
我創建了一個小提琴供您參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.