简体   繁体   English

如何将javascript变量添加到html标签

[英]How can I add javascript variable to html tag

I have a function whose name is rendered which get two params: the container is a <select> in HTML and items just is my student array of an object which contains information of each student and it has 'class' property. 我有一个函数的名称被渲染,该函数有两个参数:容器是HTML中的<select> ,而item只是我的对象数组,其中包含每个学生的信息,并且具有“ class”属性。

My idea is to create an <opgroup> tag in string and then pass it to HTML through .innerHTML . 我的想法是在字符串中创建一个<opgroup>标记,然后通过.innerHTML将其传递到HTML。 The problem is that I want to create a new <optgroup> relatively to student's class to separate each class, but I have no idea of passing object.class 's value to the <optgroup> label. 问题是我想相对于学生的班级创建一个新的<optgroup>来分隔每个班级,但是我不知道将object.class的值传递给<optgroup>标签。 Can you show me the way to pass a JavaScript variable to this <optgroup id="optgroup-class"></optgroup> string in a js file? 您能告诉我将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
}

El método unshift() agrega uno o más elementos al inicio del array, y devuelve la nueva longitud del array. Elunédodounshift()从头开始,从头到尾都是纵向数组。 Link 链接

so, you are add <optgroup id="optgroup-class"></optgroup> at index 0 因此,您将在索引0处添加<optgroup id="optgroup-class"></optgroup>

// [ '<optgroup id="optgroup-class"></optgroup>', '<option id="std-option"> name1 </option>', '<option id="std-option"> name1 </option>' ]

Try this below. 请在下面尝试。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM