简体   繁体   English

JavaScript播放列表目标元素

[英]JavaScript Playlist Target Element

I am working on a JavaScript driven audio player with a playlist. 我正在使用带有播放列表的JavaScript驱动的音频播放器。 I have a problem when I try to add a click event to the elements I want to play. 尝试将click事件添加到要播放的元素时遇到问题。

Apparently I am doing something wrong in the loop because the elements are displayed, yet not played. 显然我在循环中做错了事,因为这些元素已显示但尚未播放。 No errors in the console. 控制台中没有错误。

JSFIDDLE HERE JSFIDDLE这里

//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
    }
}

Not sure I know what you're trying to accomplish with the for loop. 不知道我是否知道您要使用for循环来完成什么。 But as I see it the problem is that you never enter the for loop. 但正如我所见,问题是您永远不会进入for循环。 If I gues correctly you're trying to get the index of the target element and do some stuff with that ? 如果我猜对了,那么您正在尝试获取目标元素的索引,并对此进行一些处理?

So going by this assumption you could use jquery and get the index of the element you clicked instead. 因此,按照这种假设,您可以使用jquery并获取您单击的元素的索引。

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

and then skip the loop. 然后跳过循环。 I can't really test this in jsfiddle because I get errors like "playlist_status" is undefined. 我无法真正在jsfiddle中对此进行测试,因为出现了诸如“ playlist_status”之类的未定义错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM