2016-12-14 75 views
2

從.js文件,我得到的專輯名稱並裝入一個選擇菜單與使用此功能:動態地從另一個動態創建的選擇在HTML/JavaScript的創建選擇框

function loadToSelect(id, list){ 
    for (var i in list) { 
    var option = document.createElement("option"); 
    option.innerText = list[i].title; 
    document.getElementById(id).appendChild(option); 
    } 
} 

什麼我現在需要做的是在另一個選擇框中加載該專輯中的歌曲。我試過如下:

此功能使用loadToSelect選擇要加載的文件「歌曲」的一部分,並從軌道

function loadToSongs(index) { 
    loadToSelect("songs", albums[index].tracks); 
    document.getElementById("songs").size = albums[index].tracks.length; 
} 

數量創建一個選項菜單下的功能應該得到所選專輯的指數並加載歌曲相應

function songsFromAlbum() { 
    loadToSongs(getElementById("albums").selectedIndex); 
} 

最後,我把這些啓動功能

loadToSelect ("albums", albums); 
document.getElementById("albums").onchange= songsFromAlbum() 

什麼工作迄今加載專輯到一個文本框,但加載歌曲似乎並沒有工作,任何幫助或建議,將不勝感激

編輯:我應該提到我不是允許使用jQuery 。

回答

2

享受

function loadToSelect(id, list){ 
 
    document.getElementById(id).innerHTML = ''; 
 
    for (var i in list) { 
 
    var option = document.createElement("option"); 
 
    option.innerText = list[i].title; 
 
    document.getElementById(id).appendChild(option); 
 
    } 
 
} 
 

 
function loadToSongs(index) { 
 
    loadToSelect("songs", albums[index].tracks); 
 
} 
 

 
function songsFromAlbum() { 
 
    loadToSongs(document.getElementById("albums").selectedIndex); 
 
} 
 

 
document.getElementById("albums").addEventListener("change", function(){ 
 
    songsFromAlbum(); 
 
}); 
 

 

 
var albums = [{title: 'Red', tracks: [{title: 'Red Song 1'}, {title: 'Red Song 2'}]}, {title: 'Blue', tracks: [{title: 'Blue Song 1'}, {title: 'Blue Song 2'}]}, {title: 'Green', tracks: [{title: 'Green Song 1'}, {title: 'Green Song 2'}]}]; 
 

 
loadToSelect ("albums", albums); 
 

 
document.getElementById("albums").onchange= songsFromAlbum()
<select id="albums"></select> 
 

 
<select id="songs"></select>

+0

Incredidble!非常感謝你,我真的很感激! – Pete