简体   繁体   English

Javascript:如果jquery GET失败,则更改CSS元素

[英]Javascript: change CSS element if jquery GET failed

I have a Javascript in my header that calls an external server to retrieve some information, like this: 我的标题中有一个Javascript调用外部服务器来检索一些信息,如下所示:

$.getJSON("https://domain.tld/json/", function (something) {
            var results = //stuff that formats the result, not relevant here;
            window.$info = results;
    }).fail(function(){
        // here's where I need the code to make the warning appear 
        });         

Then in the body I have a warning that should pop up in case the GET request failed: 然后在正文中我有一个警告,如果GET请求失败,应该弹出:

<div id="warning">Warning text</div>

Problem: the javascript is in the header and I can't change the "warning" div because it has not been created yet. 问题:javascript位于标题中,我无法更改“警告”div,因为它尚未创建。 If I use document.getElementById("warning").style.display='block'; 如果我使用document.getElementById("warning").style.display='block'; I get an error message saying it is null. 我收到一条错误消息,说它是null。

So how do I use the .fail() part of the jquery GET function to make the warning div appear (that is created later) in case the GET function has failed? 那么如何使用jquery GET函数的.fail()部分来显示警告div(稍后创建)以防GET函数失败? Or is that not possible? 或者那是不可能的? And some 'solution' I tried (don't remember what exactly) even delayed the loading of the whole page. 我试过的一些“解决方案”(不记得究竟是什么)甚至延迟了整个页面的加载。 I'd like to avoid that as well. 我也想避免这种情况。

Thank you for helping me out. 谢谢你帮助我。

You should hide your html element initialy 你应该首先隐藏你的html元素

<div id="warning" style="display:none;">Warning text</div>

And you can call show() method to display hidden element when get request failed 并且您可以调用show()方法在get请求失败时显示隐藏元素

$("#warning").show();

Your javascript is trying to execute and look for things before the DOM has loaded. 你的javascript试图在DOM加载之前执行并查找内容。 You can solve this problem by making sure your javascript only fires when the DOM is ready. 您可以通过确保您的javascript仅在DOM准备就绪时触发来解决此问题。 In jQuery you do that like this: 在jQuery中,你这样做:

$(document).ready(function(){
  //your code here
});

The native javascript version of this is much more complicated so I won't post that here. 这个本机javascript版本要复杂得多,所以我不会在这里发布。 However you could also wait for the entire page to load before executing the code like so: 但是,您也可以在执行代码之前等待整个页面加载,如下所示:

window.onload = function(){
  //your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM