开发者

transform a select list into a ul list

开发者 https://www.devze.com 2022-12-13 22:35 出处:网络
I am tryin开发者_Go百科g to clone a select list into a standard ul list for enhanced javascript select box manipulation/styling.

I am tryin开发者_Go百科g to clone a select list into a standard ul list for enhanced javascript select box manipulation/styling.

Basically, if I do this: $("#calendar select option").clone().appendTo("#test");

i get the following html

<ul id="test">
<option>All Types</option>
<option>Installation</option>
<option>Music</option>
<option>Performing Arts</option>
<option>Season</option>
<option>YUIYIYI</option>
</ul>

How can i then change all the <option> tags to be <li> tags without losing all the values?

Any help much appricated.

A.


I would recommend you to get the right formed li elements markup by traversing your options.

An example using $.map:

var listItems = $("#calendar select option").map(function(){
  return '<li>' + $(this).text() + '</li>';
}).get().join("");

$("#test").append(listItems);

Check the above snippet here.


My opinion is that the option values should be treated as rel tags for your "custom select":

var listitems = [];
$("#calendar select option").each(function() {
    var $this = $(this);
    listitems.push('<li rel="' + $this.val() + '">' + $this.text() + '</li>');
});

$('#test').html(listitems.join(""));


Something like this should work:

var list_items = '';
$("#calendar select option").each(function() {
    var $this = $(this);
    list_items += '<li rel="'+$this.val()+'">'+$this.html()+'</li>';
});
$("#test").append($(list_items));

Just as a side note, from what I recall, string concatenation and one append is usually faster than a bunch of appends or array pushes.

Credit goes to @cballou for the rel tag part...


$("#calendar select option").each(
    function(){
        html = $(this).html();
        e = document.createElement('li');
        e.setAttribute('innerHTML',html);
        $("#test").append(e);
    }
);

Not tested, but that should get you most of the way there. Good luck!


instead of...

$("#calendar select option").clone().appendTo("#test");

try...

$("#calendar select option").each(function(){
  $("<li>" + $(this).text() + "</li>").appendTo("#test");
});

Short and sweet.

0

精彩评论

暂无评论...
验证码 换一张
取 消