为什么我的 JavaScript 函数没有触发?

Why are my JavaScript functions not firing?

我正在开发一个天气应用程序,该应用程序正在 API 调用 OpenWeather 以获取天气信息(我添加了一个 API 键用于测试,但我将交换并删除这个之后)。问题是,我的功能没有触发。我可能只是错过了非常明显的...

HTML:

<div class="container-small weather">    
  <h1 class="heading-small">Weather</h1>
  <form class="change-location">
    <label for="city">Enter a location and hit enter:</label>
    <input type="text" name="city" class="weather-input">
  </form>

  <div>
    <!-- wrapper -->
    <div id="weather-img">
      <!-- show weatherState image depending on what the weather's like -->
      <!-- js will exchange class 'wimg' with sunny, rainy, etc -->
    </div>

    <!-- output the weather information -->
    <div>
      <div id="description" class="description"></div>
      <h1 id="temp" class="temp"></h1>
      <div id="location" class="location"></div>
    </div>
  </div>
</div>

JS:

const key = 'bd669dc2b57e52ed023580e893a05770';  
// fetch weather information
function weatherBallon(city) {
  console.log('weatherBallon!');
  fetch('https://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=' + key)
    .then(function(resp) {
      return resp.json()
    }) // Convert data to json
    .then(function(data) {
      //call function to output weather date to the DOM/UI
      drawWeather(data);
      console.log(data);
    })
    .catch(function(err) {
      console.log(err);
    });
}

// output the fetched weather information to the DOM/UI
function drawWeather(d) {
  var celcius = Math.round(parseFloat(d.main.temp) - 273.15);
  var fahrenheit = Math.round(((parseFloat(d.main.temp) - 273.15) * 1.8) + 32);
  var description = d.weather[0].description;

  document.getElementById('description').innerHTML = description;
  document.getElementById('temp').innerHTML = celcius + '&deg;';
  document.getElementById('location').innerHTML = d.name;

  var weatherState = document.querySelector('#weather-img');

  if (description.indexOf('rain') > 0) {
    weatherState.className = 'rainy';
  } else if (description.indexOf('cloud') > 0) {
    weatherState.className = 'cloudy';
  } else if (description.indexOf('sunny') > 0) {
    weatherState.className = 'sunny';
  } else {
    weatherState.className = 'clear';
  }

  // get user input
  const cityInput = document.querySelector('.change-location');
  console.log(cityInput);

  cityInput.addEventListener('submit', e => {
    e.preventDefault();
    let city = cityInput.city.value.trim();
    city = DOMPurify.sanitize(city);
    console.log(city);
    cityInput.reset();

    weatherBallon(city);

  });
}

我认为问题出在 cityInput 变量上,因为当我 console.log 它时它 returns 'undefined'。但我不确定为什么它不起作用。我对 .change-location 输入字段的引用有误吗?

cityInput.addEventListener('submit', e => {
    e.preventDefault();
    let city = cityInput.city.value.trim();
    city = DOMPurify.sanitize(city);
    console.log(city);
    cityInput.reset();

    weatherBallon(city)
 }

drawWeather().

里面

我觉得应该在外面。

您还应该在获取元素 cityInput 之外包括在内,以避免 undefined 错误。