有没有办法从Javascript中的数组创建无序html列表?

时间:2019-04-04 22:56:19

标签: javascript html haml

我想使用纯HTML和javascript而不是HAML。 在我处理这个表单项目之前,我像这样遍历数组

- @item1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
- item1.each_with_index do |item, i|
   %li.option
      %input.option-input{name: 'options', type: 'radio', value: i, id: "options-#{i}"}/
      %label.option-label{:for => "options-#{i}"}= item1

1 个答案:

答案 0 :(得分:0)

<script>
    (function(){
        const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
        const ul = document.createElement('UL');
        for (let i=0; i< items.length; i++){
            const item = items[i];
            const li = document.createElement('LI');
            const label = document.createElement('LABEL');
            const input = document.createElement('INPUT');
            input.value = item;
            input.setAttribute('id', 'options-' + i);
            input.setAttribute('type', 'radio');
            input.setAttribute('name', 'options');
            label.appendChild(input);
            label.setAttribute('for', 'options-' + i);
            label.appendChild(document.createTextNode(item));
            li.appendChild(label);
            ul.appendChild(li);
        }
        document.body.appendChild(ul);
    })();
</script>