通过点击按钮改变变量的值

Changing Value of variable with click on a button

本文关键字:变量 改变 按钮      更新时间:2023-09-26

我试图在按下按钮时将"unit"的值从'c'切换到'f',我只是无法让它工作。我已经花了很多时间看其他的例子,但我很想知道为什么我的解决方案不起作用。我已经设法切换按钮的值,但无法找到一种方法来实际使用按钮。loadweather函数中的值。只使用单位按钮。价值,没有用。你知道哪里出了问题吗?

我的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', '');

不知道为什么你的代码不能为你工作。

我粘贴到jsbin,它为我工作。

请看这里:http://jsbin.com/foheguzevo/edit?html,css,js,output

脚本应该是这样的:

var temp = 'c';
function change() {
    temp = temp == 'f' ? 'c' : 'f';
}
$(document).ready(function() {
    $('.btn').on('click', function() { change(); });
});

$(document).ready()只会在所有元素加载并创建后添加事件监听器