我怎样才能使这个重置按钮功能起作用?

问题描述 投票:0回答:0

我是一名初级程序员,所以请不要过多地取笑这段代码,但这是一个非常简单的练习天气 api,我只是找不到解决方案来使这个 resetFunc 不是未定义/不是函数。我

我正在寻找一种方法来使重置按钮的此功能不是未定义/不是功能。我正在尝试使 resetbtn 的此重置函数 resetFunc() 仅在 displayExecuted 标志变为真后才起作用,它一直使 newText 文本节点未定义并且我尝试在全局和本地范围内使用 newText


let newText
let weatherDisplay;
let displayExecuted = false;


function getWeather() {

let resetbtn = document.getElementById(`resetbtn`)
let wbutton = document.getElementById(`wbutton`) 
let weatherText = document.getElementById('w')




if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude; 
        const endpoint = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&hourly=temperature_2m&current_weather=true` 
    fetch(endpoint) 
        .then(res =>  res.json())
        .then(data => {
    console.log(data)
    const weather = data['current_weather'].temperature 
    console.log(weather)
        

    
    
     newText = document.createTextNode(`${weather}`)
    
    weatherDisplay = function weatherDisplay() { 
        if (!displayExecuted) {
        weatherText.querySelector('p').append(newText.nodeValue +  " "+'degrees') }
        displayExecuted = true
    }
    


    resetFunc = function resetFunc () {
       if (displayExecuted === true) {
       newText.nodeValue = " "
       }
    }
    
    
}) 
    .catch(error => {
        console.error("Error fetching data:", error)
     
    })
.catch(error => {
    console.error("Error fetching data", error)
})
    })
    wbutton.addEventListener(`click`,weatherDisplay,{once: true})
    resetbtn.addEventListener(`click`,resetFunc)
    
} else {
    console.error('Geolocation not supported in this fucking browser, dumb fuck!')

}}
getWeather()

我试过全局变量,并尝试在不同的范围内格式化函数。

javascript dom event-handling
© www.soinside.com 2019 - 2024. All rights reserved.