获取输入值并将其与 JavaScript 变量一起使用

Get input value and use it with variable with JavaScript

本文关键字:变量 JavaScript 一起 输入 获取      更新时间:2023-09-26

我有一个id="to"的输入字段,它是空的,当用户输入某些内容并按提交时,它应该更改下面脚本中的位置属性。但是,什么也没发生。

oldvalue = document.getElementById("to").value;
var newvalue;
var inputBox = document.getElementById("to");
inputBox.onchange = function(){
    newvalue = document.getElementById("to").value;
    oldvalue = newvalue;
};
$(document).ready(function() {
  $.simpleWeather({
    location: oldvalue,
    unit: 'c',
    success: function(weather) {
      html = '<h2><i class="icon-'+weather.code+'"></i> '+weather.temp+'&deg;'+weather.units.temp+'</h2>';
      html += '<ul><li>'+weather.city+', '+weather.region+'</li>';
      html += '<li class="currently">'+weather.currently+'</li>';
      $("#weather").html(html);
    },
    error: function(error) {
      $("#weather").html('<p>'+error+'</p>');
    }
  });
});

网页输入

<div class="input-group add-on">
<input type="text" class="form-control" placeholder="to: " id="to">                
<button id='tobtn' class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>               
</div>

你可以尝试这样的事情:

JavaScript:

oldvalue = document.getElementById("to").value;
var newvalue;
var inputBox = document.getElementById("to");
inputBox.onchange = function(){
    newvalue = document.getElementById("to").value;
    oldvalue = newvalue;
};
var loadWeather = function(location) {
    $.simpleWeather({
       location: location,
       unit: 'c',
       success: function(weather) {
           html = '<h2><i class="icon-'+weather.code+'"></i>  '+weather.temp+'&deg;'+weather.units.temp+'</h2>';
           html += '<ul><li>'+weather.city+', '+weather.region+'</li>';
           html += '<li class="currently">'+weather.currently+'</li>';
           $("#weather").html(html);
       },
       error: function(error) {
           $("#weather").html('<p>'+error+'</p>');
       }
   });
}
var refreshWeather = function(){
    loadWeather(oldvalue);
}
$(document).ready(function() {
   loadWeather(oldvalue);
});

.HTML:

<div class="input-group add-on">
    <input type="text" class="form-control" placeholder="to: " id="to">                
    <button id='tobtn' class="btn btn-default" type="button" onclick="refreshWeather();"><i class="glyphicon glyphicon-search"></i></button>               
</div>

我将提交按钮更改为普通按钮,因为我认为在此示例中您不需要调用服务器。

我相信

您的问题是您的 HTML 按钮设置为键入"提交"。当用户按下按钮而不是将数据提交到服务器端组件时,您似乎想在客户端(使用 JavaScript)执行操作。

尝试将类型设置为"按钮"。将单击事件绑定到按钮,并在事件处理程序中执行 $.simpleWeather 调用。这应该应该可以解决你问题。

编辑:要实际将javascript绑定到您的按钮,您可以做的一件事是:

<button onclick="refreshWeather()">Submit</button>

然后只需将您的 $.simpleWeather 代码放入该名称的函数中即可