[英]How can I add javascript variable to html tag
我有一個函數的名稱被渲染,該函數有兩個參數:容器是HTML中的<select>
,而item只是我的對象數組,其中包含每個學生的信息,並且具有“ class”屬性。
我的想法是在字符串中創建一個<opgroup>
標記,然后通過.innerHTML
將其傳遞到HTML。 問題是我想相對於學生的班級創建一個新的<optgroup>
來分隔每個班級,但是我不知道將object.class
的值傳遞給<optgroup>
標簽。 您能告訴我將JavaScript變量傳遞到js文件中的此<optgroup id="optgroup-class"></optgroup>
字符串的方法嗎?
function render(container, items) {
var htmlItems = items.map(function (item) {
return '<option id="std-option">' + item.name + '</option>';
});
htmlItems.unshift('<optgroup id="optgroup-class"></optgroup>'); //add optgroup to the first index of htmlItems
var html = htmlItems.join(''); //join all the <stringArray> to just one html tag string
container.innerHTML = html; //get that <stringArray> to .student-list-container select in html
}
Elunédodounshift()從頭開始,從頭到尾都是縱向數組。 鏈接
因此,您將在索引0處添加<optgroup id="optgroup-class"></optgroup>
// [ '<optgroup id="optgroup-class"></optgroup>', '<option id="std-option"> name1 </option>', '<option id="std-option"> name1 </option>' ]
請在下面嘗試。
function render(container, items) { let html = ''; items.forEach(e => { html += `<optgroup label="${e.name}">`; e.options.forEach(o => { html += `<option value="${o.name}">${o.name}</option>`; }); html += `</optgroup>`; }); container.innerHTML = html; } let list = [{ name: 'Swedish Cars', options: [{ name: 'Volvo' }, { name: 'Saab' } ] }, { name: 'German Cars', options: [{ name: 'Mercedes' }, { name: 'Audi' } ] }]; render(document.getElementById('my-select'), list);
<select id="my-select"></select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.