![](/img/trans.png)
[英]How to stop text overlapping icon and keep text vertically centered when wrapping, using Bootstrap 5 buttons in a flex box?
[英]How to stop the Api icon keep adding when click the buttons?
我必须创建一个带有两个按钮的 web 来显示每个城市的信息。 当我点击按钮时,每次我点击它时图标都会不断添加。 我也尝试过 if 语句,但它没有用。 有什么办法可以阻止它或其他方法来显示图标吗?
window.onload=function(){ var chooseBox = document.getElementById("output"); var tempOut = document.getElementById("temperature"); var condiOut = document.getElementById("conditions"); var locationOut = document.getElementById("location"); var weaIcon = document.getElementById("icon"); var torontBtn = document.getElementById("Toronto"); var tpeBtn = document.getElementById("Taipei"); var feelstemp = document.getElementById("feelsLike"); const myApiKey = "0730ce4dd97d237ff76898a994164939"; const toUrl = "https://api.openweathermap.org/data/2.5/weather?q=Toronto&appid=" + myApiKey + "&units=metric"; const tpeUrl ="https://api.openweathermap.org/data/2.5/weather?q=Taipei&appid=" + myApiKey + "&units=metric"; let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if ( xhr.readyState === 4 ){ if ( xhr.status === 200){ const data = xhr.response; console.log(data); const iconWea = "https://openweathermap.org/img/wn/" + data.weather[0].icon + ".png"; var elementIcon = document.createElement('img'); elementIcon.setAttribute('src', iconWea); weaIcon.appendChild(elementIcon); //SHOWASSIGNED ICON locationOut.innerHTML = data.name; tempOut.innerHTML = data.main.temp + "°C"; feelstemp.innerHTML = data.main.feels_like + "°C"; condiOut.innerHTML = data.weather[0].description; } else { locationOut.innerHTML = "API call was unsucessful"; console.log(xhr.status); } } } torontBtn.onclick = function() { chooseBox.style.display = "block"; xhr.open('GET',toUrl,true); xhr.responseType = 'json'; xhr.send(null); } tpeBtn.onclick = function () { chooseBox.style.display = "block"; xhr.open('GET',tpeUrl,true); xhr.responseType = 'json'; xhr.send(null); } };
这就是我所做的:
var iconUrl = "https://openweathermap.org/img/wn/" + data.weather[0].icon + "@2x.png";
out_icon.innerHTML = `<img src='${iconUrl}'/>`;
weaIcon.appendChild(elementIcon) 应替换为 weaIcon.innerHtml=elementIcon
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.