Javascript 如何使用json api随机更改网页的背景色?
我想执行一个javascript onload,根据这个json文件随机更改网页的背景颜色,该文件给出了随机颜色Javascript 如何使用json api随机更改网页的背景色?,javascript,html,json,Javascript,Html,Json,我想执行一个javascript onload,根据这个json文件随机更改网页的背景颜色,该文件给出了随机颜色 您还可以将所有提取逻辑提取到一个单独的函数中,并创建一个按钮,该按钮在单击时调用该函数,从而在每次单击按钮时更改背景颜色您是否测试了该按钮?然而,这并不适用于meI,只是更新了答案并进行了测试。它有效,现在就试试。如果您对我的评论中没有涉及的代码有任何其他问题,请告诉我。很抱歉,以前它不起作用,我在手机上写下了答案,无法测试 // this function will be tri
您还可以将所有提取逻辑提取到一个单独的函数中,并创建一个按钮,该按钮在单击时调用该函数,从而在每次单击按钮时更改背景颜色您是否测试了该按钮?然而,这并不适用于meI,只是更新了答案并进行了测试。它有效,现在就试试。如果您对我的评论中没有涉及的代码有任何其他问题,请告诉我。很抱歉,以前它不起作用,我在手机上写下了答案,无法测试
// 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
});
})