gpt4 book ai didi

javascript - HTML 数据转换为 JavaScript 函数问题

转载 作者:行者123 更新时间:2023-11-28 13:05:49 25 4
gpt4 key购买 nike

我有以下使用天气插件的代码( https://a12k.io/reallysimpleweather ),我的问题是我想知道如何使用通过 HTML 表单元素从用户收集的数据,如下所示,

<script>var input = document.getElementById('cityInput').value;</script>

<script>
reallySimpleWeather.weather({
//var city = "Bend, Or";
wunderkey: '', // leave blank for Yahoo API
location: input,
woeid: '', // "Where on Earth ID" optional alternative to location
unit: 'f', // 'c' also works
success: function(weather) {
html = '<h2>'+weather.temp+'°'+weather.units.temp+'</h2>';
html += '<ul><li>'+weather.city+', '+weather.region+'</li>';
html += '<li>'+weather.currently+'</li>';
html += '<li>'+weather.wind.direction+' '+weather.wind.speed+' '+weather.units.speed+'</li></ul>';
document.getElementById('weather').innerHTML = html;
},
error: function(error) {
document.getElementById('weather').innerHTML = '<p>'+error+'</p>';
}
});
</script>


</head>
<body>
<div class="container-fluid">
<div id="weather"></div>

<form>
City: <input type="text" name="city" id="cityInput">
<input type="submit" value="Submit">
</form>

</div>
</body>
</html>

我不确定我的问题是否是由于我调用的页面和 API 的加载方式引起的,但是当我在浏览器中将其全部打开时,我目前只是从插件中收到一个错误,说“接收最新天气时出现问题。请重试。”我不确定这是否是因为它在最初加载后无法更新自身而引起的,或者是否是因为我错误地将变量存储在

 location: input,

每当我点击“提交”时,都不会发生任何变化,期望 URL 本身会发生变化以添加 city=%27Bend%2C+OR%27最后或输入的城市是什么。

最佳答案

使用 JavaScript 获取值并将其放在您想要的位置:

<form action="begin-create-done.html" method="get">
City: <input type="text" name="city" id="cityInput">
<input type="submit" value="Submit">
</form>

在 JavaScript 中:

var value = document.getElementByName( "city" ).value;
// or
// var value = document.getElementById( "cityInput" ).value;

reallySimpleWeather.weather({
wunderkey: '',
location: value,
woeid: '',
unit: 'f',
success: function(weather) {
html = '<h2>'+weather.temp+'°'+weather.units.temp+'</h2>';
html += '<ul><li>'+weather.city+', '+weather.region+'</li>';
html += '<li>'+weather.currently+'</li>';
html += '<li>'+weather.wind.direction+' '+weather.wind.speed+' '+weather.units.speed+'</li></ul>';
document.getElementById('weather').innerHTML = html;
},
error: function(error) {
document.getElementById('weather').innerHTML = '<p>'+error+'</p>';
}
});

请注意,您需要使用输入标记的“id”属性才能通过 JavaScript 捕获此输入。并不是说您的代码内部已经使用了 document.getElementById() 函数。您将需要一个 div 来插入 success 函数生成的 html,并且该 div 的 id 属性必须设置为“weather”。

另请注意,reallySimpleWeather.weather 是一个接收具有各种属性的对象的函数。您无法在此对象内设置变量。这是一个语法错误。您必须在 reallySimpleWeather.weather 调用之前声明它。请看上面。

关于javascript - HTML 数据转换为 JavaScript 函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46571745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com