2016-04-10 70 views
1

我正在使用bootstrap。這是我希望所有列表項目出現的表格。如何動態地將列表數據插入到html表中

<table id="playlist_table" class="table table-bordered"> 
    <caption class="text-center">PLAYLIST</caption> 
    <thead> 
     <tr> 
      <th>Song Name</th> 
      <th>Singer</th> 
      <th>Film</th> 
     </tr> 
    </thead> 
    <tbody id="palylist_table_data"> 
    </tbody> 
</table> 

這是我的播放列表:

<ul id="playlist" class="hidden"> 
    <li Src="Ek%20duje%20ke%20vaaste%20serial%20title%20song.mp3" Title="Ek Duje Ke Vasste" Singer="Unkown" Cover="Album images/ek.jpg"> Ek Duje Ke VAste 
    </li> 
    <li Src="Lak.mp3" Title="Lakshya ko HAr haal mein Paana HAi" Singer="Shankar Mahadevan" Cover="Album images/lakshya.jpg"> LAkshya 
    </li> 
</ul> 

這是jQuery代碼我已經寫了,但我沒能獲得在表中的任何數據。

$('.playlist li').each(function(){ 
     var song = $(this).attr('Src'); 
     var title = $(this).attr('Title'); 
     var singer = $(this).attr('Singer'); 
     var cover = $(this).attr('Cover'); 

     $('#playlist_table_data').html('<tr>' + '<td>' + '*' + '</td>' + '<td>' + song + '</td>' + '<td>' + singer + '</td>' + '<td>' + title + '</td>' + '</tr>');   
    }); 
+0

使用'$( '#播放列表禮')'代替'$(」播放列表。李「)'。你沒有'.playlist class' –

+0

還有更多的問題... –

+0

@cale_b是的,你是對的 –

回答

1

你有幾個選擇的問題,以及使用替代append不正確的jQuery函數html

這裏的一個working jsFiddle

注意下面的訂正的jQuery:

// Use a document ready, to be sure it waits until all html is loaded 
jQuery(function($) { 
    // Your ul is ID playlist (#playlist), not CLASS playlist (.playlist) 
    $('#playlist li').each(function() { 
    var song = $(this).attr('Src'); 
    var title = $(this).attr('Title'); 
    var singer = $(this).attr('Singer'); 
    var cover = $(this).attr('Cover'); 

    // Your table is #playlist_table, not #playlist_table_data 
    // using .html() will replace table contents. You want .append(), to add them to the end of the table 
    $('#playlist_table').append('<tr>' + '<td>' + '*' + '</td>' + '<td>' + song + '</td>' + '<td>' + singer + '</td>' + '<td>' + title + '</td>' + '</tr>'); 

    }); 
}); 
+0

謝謝。它正在工作。 –

-1

由於播放列表是一個ID單元,而不是使用 '#''。

$('#playlist li').each(function() {...//code here}); 

和更改的最後一行類似如下:()追加(而不是HTML())

$('#playlist_table_data').append('<tr>' + '<td>' + '*' + '</td>' + '<td>' + song + '</td>' + '<td>' + singer + '</td>' + '<td>' + title + '</td>' + '</tr>'); 
+0

感謝您的幫助。 –

相關問題