gpt4 book ai didi

javascript - 单击按钮更改变量值

转载 作者:行者123 更新时间:2023-11-28 06:55:35 25 4
gpt4 key购买 nike

我试图在按下按钮时将“unit”的值从“c”切换为“f”,但我无法让它工作。我花了很多时间查看替代示例,但很想知道为什么我的解决方案无法从中学习。我已经设法切换按钮的值,但后来找不到在 loadweather 函数中实际使用 button.value 的方法。仅使用单位:button.value,不起作用。您知道可能出了什么问题吗?

我的JS是:

var temp = 'c';
function change() {
if (temp == 'f') {temp = 'c';}
else if (temp == 'c') {temp = 'f';}
}
$('.btn').on('click', function() { change (); })

function loadWeather(location, woeid) {
$.simpleWeather({
location: location,
woeid: woeid,
unit: temp,
success: function(weather) {
html = '<h2>' + weather.temp + '&deg;' + weather.units.temp + '</h2>';
html += '<ul><li>' + weather.city + ', ' + weather.region + ', ' + weather.country + '</li>';
html += '<li class="currently">' + weather.currently + '</li>';
$("#weather").html(html);

按钮 html + css 如下所示:<button class = "btn"> Toggle F/C </button>

.btn {
position: fixed;
top: 20px;
background: white;
display: block;
padding: 1px 1px 1px 1px;
}

最佳答案

如果没有看到您的问题的完整重现,我无法完全确定这个答案是否完整。但是,我有一种感觉,主要问题是您在更改变量后没有记忆起 loadWeather()

演示:http://jsfiddle.net/hopkins_matt/aaov1scu/

JS:

var temp = 'c';

function change() {
if (temp == 'f') {
temp = 'c';
} else if (temp == 'c') {
temp = 'f';
}
loadWeather('Akron, OH', '');
}
$('.btn').on('click', function () {
change();
});

function loadWeather(location, woeid) {
$.simpleWeather({
location: location,
woeid: woeid,
unit: temp,
success: function (weather) {
html = '<h2>' + weather.temp + '&deg;' + weather.units.temp + '</h2>';
html += '<ul><li>' + weather.city + ', ' + weather.region + ', ' + weather.country + '</li>';
html += '<li class="currently">' + weather.currently + '</li>';
$("#weather").html(html);
}
});
}
loadWeather('Akron, OH', '');

关于javascript - 单击按钮更改变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32594170/

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