如何使用jquery将<select>下拉列表转换为无序列表?

hig*_*ude 7 jquery

如何以此格式转换下拉列表:

<select id="yearfilter" name="yearfilter">
<option value="">All years</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
</select>
Run Code Online (Sandbox Code Playgroud)

以这种格式进入无序列表:

<ul id="yearfilter" name="yearfilter">
<li value="">All years</li>
<li value="2011">2011</li>
<li value="2010">2010</li>
<li value="2009">2009</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

使用jquery ??

Sen*_*kin 13

$('#yearfilter').parent().append('<ul id="newyearfilter" name="yearfilter"></ul>');
$('#yearfilter option').each(function(){
  $('#newyearfilter').append('<li value="' + $(this).val() + '">'+$(this).text()+'</li>');
});
$('#yearfilter').remove();
$('#newyearfilter').attr('id', 'yearfilter');
Run Code Online (Sandbox Code Playgroud)

这就是我要做的.


Jos*_*kle 13

我对这个解决方案有点讨厌,但是这个怎么样?

var rep = $("select")
          .clone()
          .wrap("<div></div>")
          .parent().html()
          .replace(/select/g,"ul")
          .replace(/option/g,"li");

$("select").replaceWith(rep);
Run Code Online (Sandbox Code Playgroud)

编辑:

差不多五年后; 是的,我讨厌这个答案.

这里有一些问题.如果你有在是这样的列表中选择选项:<option value="5">With optional engraving</option>.你会得到的.这是vanilla javascript的另一种选择(因为jQuery并不支持这个).<li value="5">Withlialengraving</li>

var parent = document.querySelector('select'),
    docFrag = document.createDocumentFragment(),
    list = document.createElement('ul');

// build list items
while(parent.firstChild) {
  // we simultaniously remove and store the node
  var option = parent.removeChild(parent.firstChild);

  // not interested in text nodes at this point
  if(option.nodeType !== 1) continue;

  // lets build a list item
  var listItem = document.createElement('li');

  // we loop through the properties of the node and
  // apply only the ones that also exist as atributes
  for(var i in option) {
    if(option.hasAttribute(i)) listItem.setAttribute(i, option.getAttribute(i));
  }

  // loop through the select children to append to the
  // list item.  We want text nodes this time.
  while(option.firstChild) {
    listItem.appendChild(option.firstChild);
  }

  // append them to the document fragment for easier
  // appending later
  docFrag.appendChild(listItem);
}

// build wrapping ul.  Same as above
for(var i in parent) {
  if(parent.hasAttribute(i)) list.setAttribute(i, parent.getAttribute(i));
}

// add the list items to the list
list.appendChild(docFrag);

// lastly replace the select node with the list
parent.parentNode.replaceChild(list, parent);
Run Code Online (Sandbox Code Playgroud)
<select id="yearfilter" name="yearfilter">
<option value="">All years</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
</select>
Run Code Online (Sandbox Code Playgroud)