2014-12-04 56 views
0

我正在使用帶有播放列表的JavaScript驅動的音頻播放器。當我嘗試向我想播放的元素添加點擊事件時遇到問題。JavaScript播放列表目標元素

顯然我在循環中做錯了什麼,因爲元素被顯示,但沒有播放。控制檯中沒有錯誤。

JSFIDDLE HERE

//object 
obj = { 
    songsrc: ["mariah_carey_all_i_want", "chris_rea_driving", "wham_last_christmas", "dean_martin_snow", "brenda_lee_rocking"], 
    title: ["Mariah Carey", "Chris Rea", "Wham", "Dean Martin", "Brenda Lee"], 
    songs: ["All I want for christmas is you", "Driving home for christmas", "Last christmas", "Let it snow", "Rocking around"], 
    images: ["mariah_carey", "wham", "chris_rea", "dean_martin", "brenda_lee"] 
} 

// the <ul> in which the li elements I have lay 
mylist.addEventListener("click", changeTrack); 

// adding the songs to the playlist 
addTrack(); 
function addTrack() { 
    for(var i = obj.title.length-1; i >= 0; i--) { 
     li = document.createElement("li"); 
     li.className = "songs_wrap"; 
     li.innerHTML = "<div class='songs_inner'>" + "<h4>"+obj.title[i]+ "</h4><p>" + obj.songs[i] + "</p></div>"; 
     mylist.appendChild(li); 
    } 
} 

// trying to make them play when I click a song (a li element) 
function changeTrack(event) { 
    var target = event.target; 
    while (target != mylist) { 
     if (target.nodeName == 'LI') 
     { 
      for(var i = target; i < obj.songsrc.length; i++) // I guess this is wrong 
      { 
       obj.images.src = "images/" + obj.images[i] + ".jpg"; 
       var title = playlist_status.innerHTML = obj.title[i]; 
       var song = playlist_song.innerHTML = obj.songs[i]; 
       audio.src = dir + obj.songsrc[i] + ext; 
       playbtn_icon.className = "icon-pause"; 
       audio.play(); 
      } 
     } 
     target = target.parentNode 
    } 
} 

回答

0

不知道我知道你想與實現for循環的東西。但正如我所看到的那樣,問題在於你永遠不會進入for循環。如果我正確地提示你正在嘗試獲取目標元素的索引,並用它來做一些事情?

因此,通過這個假設你可以使用jQuery並獲得你單擊的元素的索引。

var i = $(target).index(); 

然後跳過循環。 我不能真正在jsfiddle中測試這個,因爲我得到像「playlist_status」這樣的錯誤是未定義的。

+0

這解決了我的問題,謝謝!的確,我並不需要循環,jquery爲我做了這項工作。 – SimeriaIonut 2014-12-04 12:21:27

相關問題