Taking a comma separated list and creating a unordered list
I've got a simple list which is generated by a checkbox list. The generated code is simply this
white,blue,red,black
开发者_高级运维
I need to use jquery to wrap each of these elements in a < li > tag. How do you go through the list and use the comma as a separator? I also will need to delete the comma. Sometime there will be 1 item, sometimes 3, etc.
Thanks in advance!
<script type="text/javascript">
var mystring = 'white,blue,red,black';
mystring = '<ul><li>' + mystring.replace(/,/gi,'</li><li>') + '</li></ul>';
document.write(mystring);
</script>
Outputs:
<ul>
<li>white</li>
<li>blue</li>
<li>red</li>
<li>black</li>
</ul>
This doesn't use jquery at all :)
var el = $('#elementSelector');
var values = el.html().split(',');
el.html('<ul>' + $.map(values, function(v) {
return '<li>' + v + '</li>';
}).join('') + '</ul>');
lol, 1 character shorter than omfgroflmao
:D and no jquery goodiness
mystring = '<ul>' + mystring.replace(/(\w+),?/g, '<li>$1</li>') + '</ul>';
with jquery goodiness 1 more character shortened.. haha
myobject = $('<ul>').append(mystring.replace(/(\w+),?/g, '<li>$1</li>'));
var final_string = "<ul><li>" + myString.replace(/,/gi, '</li><li>') + "</li></ul>";
精彩评论