将innerHTML从一个元素复制到另一个元素

时间:2016-04-20 05:03:28

标签: javascript audio innerhtml

我非常喜欢新手。我一直在编写一个带有HTML,CSS和Javascript的自定义音频播放器,它只包含一个播放/暂停切换按钮和歌曲标题。如果您将鼠标悬停在歌曲标题上,则会显示包含其他歌曲标题的下拉菜单。由于下拉列表是一个包含列表项的简单无序列表,我想知道如何将音频播放器的歌曲标题空间的innerHTML设置为单击列表项的innerHTML。

HTML 
<li class="dropdownList" onclick="run">Track 1</li>
<li class="dropdownList" onclick="run">Track 2</li>
<li class="dropdownList" onclick="run">Track 3</li>

JS
var songtitle = document.getElementById('songtitle');
var dropdownList = document.getElementsByClassName('dropdownList');
function run() {
    songtitle.innerHTML = dropdownList(i).innerHTML;
}

我也试过消除HTML函数调用和纯JS

dropdownList[i].addEventListener("click", run)

以下是更多细节...

        <div id="div-player">
            <button id="pButton" class="play" onclick="playPause()"></button>
            <ul>
                <li>
                    <a href="#" id="songtitle">fill innerhtml with song title</a>
                    <ul>
                        <li class="dropdownList" onclick="run()">Track 1</li>
                        <li class="dropdownList" onclick="run()">Track 2</li>
                        <li class="dropdownList" onclick="run()">Track 3</li>
                    </ul>
                </li>
            </ul>
        </div>

JS

var audioElement = document.getElementById("audioElement");
var pButton = document.getElementById('pButton');
var songtitle = document.getElementById('songtitle');
var dropdownList = document.getElementsByClassName('dropdownList');
var i=1;

function playPause() {
    if (audioElement.paused) {
        pButton.className = "";
        pButton.className = "pause";
        if (i == 6) i = 1;
        var nextTrack = "music/track"+i+".mp3";
        var getTime = audioElement.currentTime; 
        audioElement.src = nextTrack; //currentTime resets after this statement
        audioElement.onloadedmetadata = function(){ 
            audioElement.currentTime = getTime; 
            audioElement.play();
        }
        i++;
        audioElement.addEventListener('ended', playPause);
    } else {
        pButton.className = "";
        pButton.className = "play"; 
        i--;
        audioElement.pause();
    }
}

function run() {
    //stop or pause the audio
    songtitle.innerHTML = dropdownList(i).innerHTML;
    //start the playPause function again, setting i equal to the list item number that was clicked on (for example "1" or "2" or "3")
}

2 个答案:

答案 0 :(得分:0)

你最好提供一个工作示例,因为这里的例子看起来相当不完整。例如'我'来自哪里?

但在你的例子中我会改变

function run() {
    songtitle.innerHTML = dropdownList[i].innerHTML;
}

答案 1 :(得分:0)

试试这个

var songtitle = document.getElementById('songtitle');
var dropdownList = document.getElementsByClassName('dropdownList');
function run(event) {
    songtitle.innerHTML =event.target.innerHTML;

  //console.log(event.target.innerHTML);
}
//console.log(dropdownList);

for(var i=0;i<dropdownList.length;i++){
  dropdownList[i].addEventListener("click", run);
}

https://jsbin.com/