通过点击按钮改变变量的值
Changing Value of variable with click on a button
我试图在按下按钮时将"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 + '°' + 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 + '°' + 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()
只会在所有元素加载并创建后添加事件监听器
相关文章:
- 变量dos'即使我可以返回更新后的值,也不会改变
- 角度路由:只是为了改变一些变量
- 节点中的变量.js JavaScript 不会改变
- 变量在Javascript中是如何工作的?可以在setTimeout期间更改变量值
- 两个指令引用一个变量,但第二个指令不引用;不要急于改变
- 当变量改变时,在AngularJS中更新视图
- 当绑定变量改变时,Angularjs选择不更新
- 如何在服务器变量改变值时触发jquery的变化?
- Angular在作用域变量改变后更新指令
- 当控制器$scope变量改变时,AngularJS视图没有更新
- 如何用变量改变标题栏样式
- Angular.js在变量改变后更新作用域
- 如何在作用域变量改变时继续调用函数
- 根据AngularJS变量改变DOM元素类型
- 从会话存储中使用item作为变量(改变类的可见性)
- 为什么当响应变量改变值时,这个函数不运行?
- 流星:当模板变量改变时,重新运行代码
- 宽度不随JS变量改变
- ReactJs在状态变量改变时重定向
- 每次变量改变时调用函数