1 回答
TA贡献2019条经验 获得超9个赞
试试这个。这是你的 html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search songs</title>
</head>
<body>
<div id="app">
<h1>Enter artist name or song:</h1>
<input type="text" id="term" placeholder="term">
<input type="text" id="entity" placeholder="entity">
<div class="loader"></div>
<br><br>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
和javascript:
var term = document.getElementById('term');
var entity = document.getElementById('entity');
document.addEventListener('keyup', getJson);
function getJson() {
fetch('https://itunes.apple.com/search?term='+term.value+'&entity='+entity.value)
.then(function (response) {
return response.json();
})
.then(function (data) {
let result = '';
try{
data.results.forEach(function (song) {
console.log(song);
result += `<li>${song.artistName} - ${song.trackName}</li>`;
});
}
catch{}
document.getElementById('result').innerHTML = result;
})
.catch(function (empty) {
console.log(empty);
});
}
或者如果你想要某些元素的 keyup 事件:
var term = document.getElementById('term');
var entity = document.getElementById('entity');
let termAndEntity = [term, entity];
termAndEntity.forEach(function(element){
element.addEventListener('keyup', getJson);
});
function getJson() {
fetch('https://itunes.apple.com/search?term='+term.value.toLowerCase()+'&entity='+entity.value.toLowerCase())
.then(function (response) {
return response.json();
})
.then(function (data) {
let result = '';
try{
data.results.forEach(function (song) {
console.log(song);
result += `<li>${song.artistName} - ${song.trackName}</li>`;
});
}
catch{}
document.getElementById('result').innerHTML = result;
})
.catch(function (empty) {
console.log(empty);
});
}
添加回答
举报