简体   繁体   中英

JavaScript target data on child element

I am working on an audio player based on JavaScript. I am trying to make a playlist for the audio player and I succeded with select and option (html), however I can't style those. So I tried with an ul and li.

So I have the HTML markup :

<ul id="mylist">
    <li data="Another_Song" class="songs_wrap">
        <div class="songs_inner">
            <h4>Song #1</h4>
            <p>Some song details</p>
        </div>
    </li>
</ul>

And the JavaScript:

function initAudioPlayer() {
    var audio, dir, ext, mylist, mylist_li;

    ext = ".mp3";
    dir = "audio/";

    audio = new Audio();
    audio.src = dir+"My_Song"+ext;
    audio.loop = false;

    //Object ref
    mylist = document.getElementById("mylist");
    mylist_li = mylist.getElementsByTagName("li"); //targeting the li elements

    //Event handling
    mylist.addEventListener("change", changeTrack);
    mylist_li.addEventListener("click", doSomethingElse); //not sure about what it should do in corelation with the changetrack function i already have on the event.

    //Functions
    function changeTrack(event){
        audio.src = dir+event.target.data+ext;
        audio.play();
    }

}
window.addEventListener("load", initAudioPlayer);

Now when I click the li, the song should change to audio/Another_Song.mp3 , but it doesn't. I believe what I am doing wrong is targeting the "data" from the li.

Anybody has any idea?

This is how you should handle song selection in your case. Note that you must listen onclick event and select event target properly:

//Event handling
mylist.addEventListener("click", changeTrack);

//Functions
function changeTrack(event) {
    var target = event.target;
    while (target !== mylist) {
        if (target.nodeName == 'LI') {
            audio.src = dir + target.getAttribute('data') + ext;
            audio.play();
        }
        target = target.parentNode
    }
}

Note the while loop. It' very important to realized that click event will originally happen on some nested element (not li ). It means that event.target will be for example H4 or P element, not LI as you expect. So you have to walk up the DOM tree until you find closest LI node.

Finally you should use getAttribute method to read attribute data , since there is no such property as data .

Demo: http://jsfiddle.net/6fryqatq/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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