我想基于此json文件执行javascript onload来随机更改网页的背景颜色。
答案 0 :(得分:0)
// this function will be triggered when the page loads. Every time you refresh the page a new background color will be set because this function will be invoked
window.addEventListener('load', function() {
// fetch is in charge of getting the data from the API
fetch('http://api.creativehandles.com/getRandomColor') // Call the fetch function passing the url of the API as a parameter
.then(function(response) {
response.json().then(function(data){
let color = data["color"];
document.body.style.backgroundColor = color;
})
})
.catch(function() {
// This is where you run code if the server returns any errors
});
})
您还可以将所有提取逻辑提取到一个单独的函数中,并创建一个按钮,该按钮在单击时调用该函数,从而每次单击按钮时都会更改背景色