Home  >  Q&A  >  body text

javascript - filtering and rendering of arrays

var data = [{

    label: '分类一',
    value: '0'
}, {
    label: '分类二',
    value: '1'
}, {
    label: '分类三',
    value: '2'
}, {
    label: '分类四',
    value: '3'
}, {
    label: '分类五',
    value: '4'
}, {
    label: '分类六',
    value: '5'
}]

<p class="text">

<span>0</span>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>

</p>

Please tell me how to render the corresponding label value in dom based on the value in the data in the simplest way? ? The data is uncertain, there may be more than ten or twenty

in it
仅有的幸福仅有的幸福2647 days ago858

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-06-26 10:54:24

    The method above can be done, but this is equivalent to registering a variable every time, adding a span node to .text every time, and manipulating the DOM, which causes a lot of overhead! I personally recommend using the following method.

    var opText= document.querySelector('.text'),var _text="";
    data.forEach(function(item){
        //把每一次遍历的label加上节点,再储存在_text上。
        _text += '<span>'+item.label+'</span>';
    });
    //最后直接把_text赋值到opText.innerHTML上。
    opText.innerHTML=_text ;
    

    reply
    0
  • PHP中文网

    PHP中文网2017-06-26 10:54:24

    var container = document.querySelector('.text')
    data.forEach(function(item){
        var span = document.createElement('span')
        span.innerHTML = item.label
        span.setAttribute('value', item.value)
        container.appendChild(span)
    })

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-26 10:54:24

    The methods above are all feasible, but the first two methods have their own advantages and disadvantages in performance under Firefox and Chrome. Now the common practice is to create a new blank document fragment (DocumentFragment).

    const $container = document.querySelector('.text');
    const fragment = document.createDocumentFragment();
    data.map(item => {
        let span = document.createElement("span");
        span.textContent = item;
        fragment.appendChild(span);
    });
    $container.appendChild(fragment);

    reply
    0
  • typecho

    typecho2017-06-26 10:54:24

    var data = [{
        label: '分类一',
        value: '0'
    }, {
        label: '分类二',
        value: '1'
    }]
    
    // 根据value获取dataList中对应的项
    function getLabelByValue(dataList, value) {
      return dataList.find(function (item) {
        return item.value === value // 这里使用的强等,根据情况可选 ==
      })
    }
    
    // 省略DOM操作
    let label = getLabelByValue(data, '0') // 分类一

    reply
    0
  • Cancelreply