gpt4 book ai didi

javascript - 单击按钮更改背景图像(使用 jQuery 和 API)

转载 作者:行者123 更新时间:2023-12-02 14:55:29 25 4
gpt4 key购买 nike

我正在使用一个 API,该 API 返回随机图像的随机 URL,并将其设置为正文的背景图像。我怎样才能在每次点击按钮后改变它?我有下面的代码,但这不起作用。

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)');

});


};

我在按钮上使用 jQuery 单击事件来调用该函数。

$("#button").on("click", function() {


changeImage();


});

});

函数每次都会加载一个带有图像的新 JSON 对象,但背景图像不会改变...

最佳答案

正如 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 +')');

});
};

关于javascript - 单击按钮更改背景图像(使用 jQuery 和 API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35850270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com