繁体   English   中英

单击按钮更改变量的值

[英]Changing Value of variable with click on a button

我试图在按下按钮时将“单位”的值从“ c”切换为“ f”,但我无法使其正常工作。 我花了很多时间研究其他示例,但很想知道为什么我的解决方案无法从中学习。 我设法切换了button的值,但是找不到在loadweather函数中实际使用button.value的方法。 仅使用unit: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; 
}

不知道为什么您的代码对您不起作用。

我粘贴到jsbin中,它对我有用。

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

如果没有完全解决您的问题,我不能完全确定这个答案是否完整。 但是,我觉得主要的问题是您在更改变量后没有重新调用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', '');

脚本应如下所示:

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

$(document).ready()仅在加载和创建所有元素之后才添加事件侦听器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM