简体   繁体   English

子元素上的JavaScript目标数据

[英]JavaScript target data on child element

I am working on an audio player based on JavaScript. 我正在基于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. 我正在尝试为音频播放器创建播放列表,但成功使用了select和option(html),但是无法为它们设置样式。 So I tried with an ul and li. 因此,我尝试了ul和li。

So I have the HTML markup : 所以我有HTML标记:

<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: 和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. 现在,当我单击li时,歌曲应该更改为audio / Another_Song.mp3,但是没有。 I believe what I am doing wrong is targeting the "data" from the li. 我相信我做错了针对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: 请注意,您必须监听onclick事件并正确选择事件目标:

//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. 注意while循环。 It' very important to realized that click event will originally happen on some nested element (not li ). 意识到click事件最初会发生在某些嵌套元素(不是li )上,这一点非常重要。 It means that event.target will be for example H4 or P element, not LI as you expect. 这意味着event.target将是H4P元素,而不是您期望的LI So you have to walk up the DOM tree until you find closest LI node. 因此,您必须走到DOM树,直到找到最近的LI节点。

Finally you should use getAttribute method to read attribute data , since there is no such property as data . 最后,应该使用getAttribute方法读取属性data ,因为没有诸如data这样的属性。

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

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

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