.val()不指定返回新变量

时间:2016-05-19 21:02:25

标签: javascript jquery variables

此拉链将保持为0,无论“输入”的值是什么。我怀疑它与新的值分配给zip后apiAddress没有更新zip有关。任何人都可以解释发生了什么吗?

$(document).ready(function() {
    zip = 0;
    apiAddress = "api.openweathermap.org/data/2.5/weather?zip=" + zip;

    $("#submit").on("click", function() {
        zip = $("input").val();
        $("#temperature").html(apiAddress);
    });
}); 

2 个答案:

答案 0 :(得分:2)

您正在将zip变量添加到错误位置的网址中。此外,关心变量范围也更好。试试这个:

$(document).ready(function() {
    var zip = 0;

    $("#submit").on("click", function() {
        zip = $("input").val();
        apiAddress = "api.openweathermap.org/data/2.5/weather?zip=" + zip;
        $("#temperature").html(apiAddress);
    });
}); 

答案 1 :(得分:0)

首先,使用console.log()查看$("input").val();返回的内容是一种很好的做法。将以下行添加到您的代码中并检查您的浏览器控制台以查看提交后记录的值:

$(document).ready(function() {
    zip = 0;

    $("#submit").on("click", function() {
        console.log( $("input").val() ); //Add this line
        zip = $("input").val();
        apiAddress = "api.openweathermap.org/data/2.5/weather?zip=" + zip;
        $("#temperature").html(apiAddress);
    });
}); 

html中可能有多个<input>标记。尝试为其提供<input id="inp1">之类的ID,并将您的javascript代码更改为:

zip = $("#inp1").val();