[英]Anchor with onclick event works only once
Im trying to change temperature from celsius to farenheit and viceversa, but when i try it works only once, changes from celsius to farenheit and stays there. 我试图将温度从摄氏温度更改为华氏温度,反之亦然,但是当我尝试仅将其运行一次时,我将摄氏温度更改为华氏温度并保持不变。 Here is my page : http://codepen.io/Juan1417/pen/zKZkxy .
这是我的页面: http : //codepen.io/Juan1417/pen/zKZkxy 。
and the code: 和代码:
$(document).ready(function(){
var temp;
var long;
var lat;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
lat=position.coords.latitude;
long=position.coords.longitude;
var api="http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&appid=c873adc18574701f4fb0abe01d927819";
$.getJSON(api,function(data){
var city =data.name;
var country=data.sys.country;
var weather=data.weather[0].main;
temp=data.main.temp;
addIcon(weather);
document.getElementById('location').innerHTML =city+", "+country;
document.getElementById('temperature').innerHTML =(temp-273.13)+"<a id='anc' href='#'> Cº</a>";
$("#anc").click(function(e){
if(document.getElementById('anc').innerHTML==" Cº") document.getElementById('temperature').innerHTML =(temp*1.8+32)+"<a id='anc' href='#'> Fº</a>";
else document.getElementById('temperature').innerHTML =(temp-32/1.8)+"<a id='anc' href='#'> Fº</a>";
});
});
});
}
function addIcon(weather) {
switch(weather){
case 'Dizzle':
document.getElementById('animation').innerHTML ="<div class='icon sun-shower'><div class='cloud'></div><div class='sun'><div class='rays'></div></div><div class='rain'></div></div>";
break;
case 'Rain':
document.getElementById('animation').innerHTML ="<div class='icon rainy'><div class='cloud'></div><div class='rain'></div></div>";
break;
case 'Snow':
document.getElementById('animation').innerHTML ="<div class='icon flurries'><div class='cloud'></div><div class='snow'><div class='flake'></div><div class='flake'></div></div>>/div>";
break;
case 'Clear':
document.getElementById('animation').innerHTML ="<div class='icon sunny'><div class='sun'><div class='rays'></div></div></div>";
break;
case 'Thunderstom':
document.getElementById('animation').innerHTML ="<div class='icon thunder-storm'><div class='cloud'></div><div class='lightning'><div class='bolt'></div><div class='bolt'></div></div></div>";
break;
default:
}
}
});
You're re-creating the <a>
that the event is attached to. 您正在重新创建事件附加到的
<a>
。 You need to either not overwrite the element on every click, or instead of listening for a click on the element, listen for it on the document and see if it happened to land on that element. 您要么不必在每次单击时都覆盖该元素,要么要侦听该元素,而不是监听该元素的单击,而是查看它是否恰好落在该元素上。
replace 更换
$("#anc").click(function(e){
with 与
$(document).on("click", "#anc", function(){
see: jQuery's .on()
请参阅: jQuery的
.on()
Also, your if/else were both showing Fereheit. 另外,您的if / else都在显示Fereheit。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.