【问题标题】:Changing a css background image with WordPress REST API (JSON)使用 WordPress REST API (JSON) 更改 CSS 背景图像
【发布时间】:2017-12-22 07:10:31
【问题描述】:

我设法在我的 console.log 上显示了该值,但是当我使用从 WordPress REST API 提取的值来更改 CSS 背景图像时,我得到了一个“未定义”值。我正在尝试创建静态 HTML,但在我的网站上显示博客特色图片。

JS:

var newImage;
var postRequest = new XMLHttpRequest();
postRequest.open('GET','http://method.com.sg/post/wp-json/wp/v2/posts');
postRequest.onload = function(){
var ourData = JSON.parse(postRequest.responseText);
newImage = ourData[0].better_featured_image.source_url;

console.log(newImage); //Will output the hyperlink
};
alert(newImage); // Output Undefined
postRequest.send();

//Unable to work
$('.container.withBg.post').css('background-image', 'url('+newImage+')');

【问题讨论】:

    标签: jquery json wordpress rest api


    【解决方案1】:

    这可能是因为 alert() 没有所需的 url,该 url 只有在请求加载后才可用,但警报不会等待该任务完成并且会过早执行。 您可以尝试创建一个虚拟函数来处理 bg 图像的更改,一旦 url 可用,它将被调用,如下所示:

    var newImage;
    var postRequest = new XMLHttpRequest();
    postRequest.open('GET','http://method.com.sg/post/wp-json/wp/v2/posts');
    postRequest.onload = function(){
    var ourData = JSON.parse(postRequest.responseText);
    newImage = ourData[0].better_featured_image.source_url;
    
    console.log(newImage); //Will output the hyperlink
    
    //Make a function call here to change the background url
    change_background(newImage);
    };
    postRequest.send();
    
    function change_background(newImage){
        alert(newImage); // Output Undefined
        $('.container.withBg.post').css('background-image', 'url('+newImage+')');
    }
    

    您可以将函数名称更改为您想要的任何名称。

    【讨论】:

    • 啊,行得通!虚拟函数救了我的命。谢谢@yamu Yamu。
    猜你喜欢
    • 1970-01-01
    • 2014-01-19
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多