将ul li list转换为Select下拉列表

时间:2017-02-08 17:31:53

标签: select html-lists html-select

我有以下结构HTML代码

<ul id="list_abcxyz">
        <li class="label even-row">
                    <a class="label-link lia-link-navigation" rel="tag" id="link_c19bf51ba9103c" href="test.html">Label One<wbr></a>
                        <span class="label-count">(1)</span>
        </li>

        <li class="label odd-row">  
                    <a class="label-link lia-link-navigation" rel="tag" id="link_c19bf51ba9103c_0" href="test2.html">Label Two<wbr></a>
                    <span class="label-count">(1)</span>
        </li>
        <li class="label even-row">
                    <a class="label-link lia-link-navigation" rel="tag" id="link_c19bf51ba9103c_1" href="test3.html">Label Three<wbr></a>
                        <span class="label-count">(1)</span>
        </li>

如何将其转换为选择下拉菜单?我尝试过遵循社区指南。但那些没有用。我猜是因为额外的span标签。但我也需要那个span标签。

我们如何将其转换为使用JS选择选项下拉?

谢谢。

1 个答案:

答案 0 :(得分:0)

这样的事情应该让你开始。如果您遇到<span>的问题,那么您可以使用textContent属性获取所有不包含html标签的文本,然后使用replace()和trim()删除所有多个空格。< / p>

var myform = document.getElementById('myform'),
    items = document.getElementById('list_abcxyz').getElementsByTagName('li'),
    select = document.createElement('select'),
    len = items.length,
    option;

for(var i = 0; i < len; i++) {
  option = document.createElement('option');
  var label = items[i].textContent.replace(/\s\s+/g," ").trim(),
      link = items[i].getElementsByTagName('a')[0].href;
  
  option.textContent = label;
  option.value = link;
  
  select.appendChild(option);
  
}

myform.appendChild(select);

select.addEventListener('change',function(evt){
  var selectedLink = this.options[this.selectedIndex].value;
  console.log(selectedLink);
  
  location.href = selectedLink;
});
<ul id="list_abcxyz">
        <li class="label even-row">
                    <a class="label-link lia-link-navigation" rel="tag" id="link_c19bf51ba9103c" href="test.html">Label One<wbr></a>
                        <span class="label-count">(1)</span>
        </li>

        <li class="label odd-row">  
                    <a class="label-link lia-link-navigation" rel="tag" id="link_c19bf51ba9103c_0" href="test2.html">Label Two<wbr></a>
                    <span class="label-count">(1)</span>
        </li>
        <li class="label even-row">
                    <a class="label-link lia-link-navigation" rel="tag" id="link_c19bf51ba9103c_1" href="test3.html">Label Three<wbr></a>
                        <span class="label-count">(1)</span>
        </li>
</ul>

<form id="myform">
  
</form>