【问题标题】:Update the global variable after document is ready and use this variable to change HTML with Jquery文档准备好后更新全局变量并使用此变量通过 Jquery 更改 HTML
【发布时间】:2018-10-23 11:36:53
【问题描述】:

我有非常基本的代码,但我不知道我在这里做错了什么。我在编程方面也有点新手,并试图通过练习来提高自己。

首先我创建了空字符串城市变量,并使用从 API 接收到的城市信息对其进行了更新。变量更新后,我想将该变量用作另一个 API 中的输入来获取该城市的天气。

但是我试图查看变量是否在位置 API 之后实际更新但无法管理它?你们能帮我解决这个问题吗

var city = "";

$.get("https://api.ipdata.co", function (response) {
    city = $("#city").html(response.city + ", " + response.region);
}, "jsonp");

$(document).ready(function() {
  $("#trial").html(city);
});
body {
    background-color: #000000;
    color: white;
    text-align: center;
}

.title {

    font-size: 66px;
    margin-top: 5px;
    font-weight: 500;
}

#city {
    font-size: 33px;
}

#trial {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
        <h1 class="title">
            Weather App
        </h1>
        <div id="city"></div>
        <h1 id="trial">yy</h1>
    </div>

【问题讨论】:

    标签: javascript jquery html css variables


    【解决方案1】:

    .html() 返回一个 jQuery 对象,因此您的 city 变量将是一个 jquery 对象,而不是您期望的字符串。如果您将响应值分配给变量,那么它将被设置。

    let city = ''
    
    $(document).ready(function() {
        $.get("https://api.ipdata.co", function (response) {
            city = response.city + ", " + response.region;
            $("#city").html(city);
            console.log(city);
            $("#trial").html(city);
        }, "jsonp");
    });
    

    您正在做的是运行您的 ajax,这可能会或可能不会在 .ready() 被触发之前完成。您需要等到 ajax 完成并且回调已经运行,然后才能测试城市。

    【讨论】:

    • 感谢您的清晰解释。这解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多