TypeError:无法将属性'textContent'设置为null; temperatureDegree.textContent =温度

时间:2020-01-22 04:41:00

标签: javascript

我正在制作一个天气应用程序,并且无法编辑“ textContent”,而不会出现以下错误:temperatureDegree.textContent = temperature

window.addEventListener("load", ()=> {
    let long
    let lat
    let temperatureDescription = document.querySelector("temperature-description")
    let temperatureDegree = document.querySelector("temperature-degree")
    let locationTimezone = document.querySelector("location-timezone")

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            long = position.coords.longitude
            lat = position.coords.latitude

            const proxy = "http://cors-anywhere.herokuapp.com/"
            const api = `${proxy}https://api.darksky.net/forecast/503a88031807535a11c0654c147002d5/${lat},${long}`
            fetch(api)
            .then(response => {
                return response.json()
            })
            .then(data => {
                console.log(data)
                const {temperature, summary} = data.currently
                //Set DOM Elements from the API
                temperatureDegree.textContent = temperature
            })
        })
    } else {
        h1.textContent = "We can't find your location...make sure it is activated."
    }
})

2 个答案:

答案 0 :(得分:2)

您必须在选择器符号之前。如果 temperature-degree id ,则在其前面加上井号(#

let temperatureDegree = document.querySelector("#temperature-degree")

或者如果它是 class ,则在其前面加上点(.)符号

let temperatureDegree = document.querySelector(".temperature-degree")

您还必须对其他元素执行相同的操作。

答案 1 :(得分:0)

如果您使用Class选择DOM元素,请使用

let temperatureDegree = document.querySelector(".temperature-degree");

如果您使用id,请使用

let temperatureDegree = document.querySelector("#temperature-degree");