2013-02-06 35 views
1

我有一塊文本,我想更改爲ul列表。 要確定文字會破碎的地方,我以爲我可以使用像/ 這樣的字符,所以文字可能是。jQuery - 從文本創建ul列表

<p> 
     /Red Car/Green Car/Black Car 
    </p> 

我需要一個像這樣的列表。

<ul> 
     <li>Red Car</li> 
     <li>Green Car</li> 
     <li>Black Car</li> 
    </ul> 

我一直在嘗試這樣做。

 $(function(){ 
     var list = ''; 
     $('.whatWeDo').find('=').each(function(){ //.whatWeDo id the <p> 
      list += '<li>' + $(this).next() + '</li>'; 
     }); 
     var theList = $('ul').append(list); 
     $('.whatWeDo').html(theList); 
     }) 
+1

什麼是這裏的問題?請編輯帖子,詳細說明您正在查找的行爲,您沒有看到什麼行爲,任何錯誤等。 –

回答

2

試試這個:

var items = $('p').text().trim().split('/'); 
$('p').replaceWith('<ul>'); 
for (var i = 0; i < items.length; i++) { 
    if(items[i].length >0) $('ul').append('<li>' + items[i] + '</li>'); 
} 

jsFiddle example

1

.find()尋找一個jQuery選擇,而不是文字。

試試這個,它謊稱原始元素具有original一個id:

jQuery(function ($) { 

    // Get your original list, and its text 
    var $original = $('#original'); 
    var text = $original.text(); 

    // Split the text at every '/', putting the results into an array 
    var listItems = text.split('/'); 

    // Set up a new list 
    var $list = $('<ul></ul>'); 

    // Loop through the list array, adding an <li> for each list item 
    listItems.each(function(item){ 
     $list.append('<li>' + item + '</li>'); 
    }); 

    // Replace the old element with the new list 
    $original.replaceWith($list); 

});