[英]Change background image with click on button (using jQuery and API)
I am using an API that returns an random URL to a random image and set that to the background-image of the body. 我正在使用一个API,该API将随机URL返回到随机图像,并将其设置为主体的背景图像。 How can I make that to change after every click of a button?
每次单击按钮后如何更改? I have the code below, but that doesnt work.
我有下面的代码,但这不起作用。
function changeImage() {
$.getJSON("https://api.unsplash.com/photos/random?client_id=336b527b2e18d045045820b78062b95c825376311326b2a08f9b93eef7efc07b", function(result){
var randomPhoto = result.urls.full;
console.log(randomPhoto);
$('body').css('background-image', 'url(randomPhoto)');
});
};
I use a jQuery click event on the button to call the function. 我在按钮上使用jQuery click事件来调用该函数。
$("#button").on("click", function() {
changeImage();
});
});
function loads a new JSON object with image every time, but the background-image doesnt change... 函数每次都会使用图像加载一个新的JSON对象,但背景图像不会改变...
As DynoMyte suggested, you should do this instead: 正如DynoMyte建议的那样,您应该改为:
function changeImage() {
var src = "https://api.unsplash.com/photos/random?client_id=336b527b2e18d045045820b78062b95c825376311326b2a08f9b93eef7efc07b";
$.getJSON(src, function(result){
$('body').css('background-image', 'url('+ result.urls.full +')');
});
};
Change this: 更改此:
$('body').css('background-image', 'url(randomPhoto)');
To this: 对此:
$('body').css('background-image', 'url('+randomPhoto+')');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.