Convert comma separated list to Unordered List [cl

2019-04-16 21:00发布

Looking for any PHP, Jquery, javascript solution to take data separated by commas and turn it into an unordered list.

To explain further, I have imported a CSV file into wordpress and one element block contains lots of data that is comma separated and I need it to display as a list.

All help is appreciated!

3条回答
祖国的老花朵
2楼-- · 2019-04-16 21:30

In PHP

$list = 'item1,item2,item3,item4';
$list = explode(',', $list);
shuffle($list);
$html = '<ul>';
foreach($list as $item) {
    $html .= '<li>' . $item . '</li>';
}
$html .= '</ul>';

print $html;

In JavaScript

var list = 'item1,item2,item3,item4';
list = list.split(',');
list.sort(function() { return 0.5 - Math.random() });
var html = '<ul>';

 for(var i=0; i<list.length; i++) {
    html += '<li>' + list[i] + '</li>';
  }

html += '</ul>';
查看更多
forever°为你锁心
3楼-- · 2019-04-16 21:37

There are cleaner ways to write this, but hopefully this will give you an idea of how it can be done using jQuery.

$(function(){
  $csv = $("#csv")
  items = $csv.text().split(",")
  $csv.replaceWith($("<ul/>"))
  items.forEach(function(item){
      $("ul").append("<li>"+item+"</li>")
  })
})

And here's the fiddle: http://jsfiddle.net/JmwDw/

查看更多
Rolldiameter
4楼-- · 2019-04-16 21:39

HTML

<ul id="ul-test">
</ul>

JavaScript

var CSV = "a,b,c,d,e";
var arrCSV = CSV.split(','),
    ul = document.getElementById("ul-test");

for (var i = 0, len = arrCSV.length; i < len; i++) {
    var li = document.createElement("li");
    var text = document.createTextNode(arrCSV[i]);
    li.appendChild(text);
    ul.appendChild(li);
}

JSFiddle

查看更多
登录 后发表回答