Ajax内置的选项列表返回零值



我是javaScript的新手。我正在使用Ajax请求端点信息。我会根据结果构建我的选项列表,以端点形式构建我的选项列表,但我无法让选择工作。

我想根据选项的值从选项列表中获取值

var xhr = new XMLHttpRequest();
var eId;
xhr.onload = function() {
    responseObject = JSON.parse(xhr.responseText);
    // build dropdown
    var artistName = '';
    artistName += '<form name="jump" id="formArtist" class="center">' +
        '<select id="artistList" name="menu">' +
        '<option value="#">Choose Artist:</option>';
    for (var i = 0; i < responseObject.length; i++) {
        artistName += '<option value="'+ responseObject[i].id +'">' + responseObject[i].name + ' ';
        artistName += ' ' + responseObject[i].surname + '</option>';
    }
    artistName += '</select></form></p>';
    var elSelectArtist = document.getElementById('artistList');
    elSelectArtist.addEventListener('change', function() {
        alert(this.value);
        eId = this.value;
    }, false);
    document.getElementById('artists').innerHTML = artistName;
};
xhr.open('GET', 'http://localhost:8080/api/artists', true);
xhr.send(null);

我确实希望从选项列表中获得值。

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
Vilken artist:
<script src="js/artists.js"></script>
List of artists:
<div id="artists"></div>
</body>
</html>
var xhr = new XMLHttpRequest();
var eId;
xhr.onload = function() {
    responseObject = JSON.parse(xhr.responseText);
    // build dropdown
    var artistName = '';
    artistName += '<form name="jump" id="formArtist" class="center">' +
        '<select id="artistList" name="menu">' +
        '<option value="#">Choose Artist:</option>';
    for (var i = 0; i < responseObject.length; i++) {
        artistName += '<option value="'+ responseObject[i].id +'">' + responseObject[i].name + ' ';
        artistName += ' ' + responseObject[i].surname + '</option>';
    }
    artistName += '</select></form></p>';
    document.getElementById('artists').innerHTML = artistName; //changed position of this
    var elSelectArtist = document.getElementById('artistList'); //and this
    elSelectArtist.addEventListener('change', function() {
        alert(this.value);
        eId = this.value;
    }, false);        
};
xhr.open('GET', 'http://localhost:8080/api/artists', true);
xhr.send(null);

您的id="artistList"仍然只是一个变量,如果您先将其添加到DOM,然后引用它,然后起作用。