gpt4 book ai didi

javascript - 无法调用 null 错误的方法 'addEventListener'

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:18:45 24 4
gpt4 key购买 nike

我写了一些 javascript 从 url 中获取天气信息。但是谷歌浏览器显示错误:

Uncaught TypeError: Cannot call method 'addEventListener' of null weather.html:37
(anonymous function)

有什么解决这个问题的建议吗?谢谢!

<html>
<head>
<title>My weather</title>
<script type="text/javascript">
function fetchWeather(){
var xmlHttp = new XMLHttpRequest(); // Initialize our XMLHttpRequest instance
xmlHttp.open("GET", "http://classes.engineering.wustl.edu/cse330/content/weather_json.php", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);

}

function ajaxCallback(event){
var htmlParent = document.getElementById("weatherWidget"); // Get the HTML element
var jsonData = JSON.parse(event.target.responseText);

var loc = document.getElementById("weatherWidget").getElementsByClassName("weather-loc")[0];
loc.appendChild(document.createTextNode(jsonData.location.city+" "+jsonData.location.state));

var humidity = document.getElementById("weatherWidget").getElementsByClassName("weather-humidity")[0];
humidity.appendChild(document.createTextNode("Humidity: "+jsonData.atmosphere.humidity+"%"));

var temp = document.getElementById("weatherWidget").getElementsByClassName("weather-temp")[0];
temp.appendChild(document.createTextNode("Currently: "+jsonData.current.temp));

var tomorrow = document.getElementById("weatherWidget").getElementsByClassName("weather-tomorrow")[0];
tomorrow.appendChild(document.setAttribute("src", jsonData.current.temp));
tomorrow.alt = jsonData.tomorrow.text;
tomorrow.src = "http://us.yimg.com/i/us/nws/weather/gr/"+jsonData.tomorrow.code+"ds.png"
var dayaftertomorrow = document.getElementById("weatherWidget").getElementsByClassName("weather-dayaftertomorrow")[0];
dayaftertomorrow.appendChild(document.setAttribute("src", jsonData.current.temp));
dayaftertomorrow.alt = jsonData.dayafter.text;
dayaftertomorrow.src = "http://us.yimg.com/i/us/nws/weather/gr/"+jsonData.dayafter.code+"ds.png"

}

document.getElementById("update").addEventListener("click", fetchWeather, false); // bind fetchWeather() to the DOMContentLoaded event
//so that your weather widget is automatically initialized
//when the page is loaded
</script>
</head>
<body>

<div class="weather" id="weatherWidget">
<div class="weather-loc"></div>
<div class="weather-humidity"></div>
<div class="weather-temp"></div>
<img class="weather-tomorrow" />
<img class="weather-dayaftertomorrow" />
</div>
<button id="update">Update</button>

</body>
</html>

最佳答案

update当您尝试访问它时,该元素还不存在。

要么把 document.getElementById('update')... <body> 末尾的行元素,或将其放在 window.onload 中处理程序。

关于javascript - 无法调用 null 错误的方法 'addEventListener',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17756251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com