Javascript 错误 - 页面加载时发生事件侦听器错误

Javascript error - Event Listener error on page load

我正在开发一个天气应用程序,但在页面加载后出现此错误 “未捕获的类型错误:无法读取 属性 'addEventListener' of null”第 36

这里是 Html 的代码片段:

<div class="weather - app">
          <div class="panel">
            <form >
                <input type="text"
                       class="search"  
                       placeholder="Search Location .."/>
                <button type="submit"
                        class="submit">
                    <i class="fa fa-search"></i>
                </button>
            </form>
            <ul class="cities">
                <li class="city">Paris</li>
                <li class="city">Las Vegas</li>
                <li class="city">Japan</li>
                <li class="city">Sfax</li>
            </ul>
            
        </div>
    </div>
    <script src = "main.js" ></script>`

................................................ .....................

并且对于 main.js:


const app = document.querySelector('.weather-app');
const form = document.querySelector('.form');
const search = document.querySelector('.search');
const btn = document.querySelector('.submit');
const cities = document.querySelectorAll('.city');



//add sumbit event to the form
form.addEventListener('submit', (e) => {
    e.preventDefault();

    //if input field(search bar) empty throw an alert
    if (search.value.length == 0) {
        alert('Please type in a City name !');
    } else {
        //change default city name to the one written in search bar 
        cityInput = search.value;
        search.value = "";
        app.style.opacity = "0";
    }
});

querySelector 使用 CSS 选择器在您的页面中查找元素, 您传递的选择器是 .form,这意味着 找到一个名为 form 的带有 class 的元素,并且这不会出现在您的 HTML 任何地方,所以正确的选择器是没有 . 的 'form' 因为 . 表示 class 搜索

所以完整代码是

const form = document.querySelector('form');

或者您可以将 class 添加到您的表单中

<form class="form">
...

有关 CSS 选择器的更多详细信息,请参阅此 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

您的 html

中没有 .form class
<div class="weather - app">
          <div class="panel">
            <form >
                <input type="text"
                       class="search"  
                       placeholder="Search Location .."/>
                <button type="submit"
                        class="submit">
                    <i class="fa fa-search"></i>
                </button>
            </form>
            <ul class="cities">
                <li class="city">Paris</li>
                <li class="city">Las Vegas</li>
                <li class="city">Japan</li>
                <li class="city">Sfax</li>
            </ul>
            
        </div>
    </div>
    <script src = "main.js" ></script>

删除 .如果您想在 DOM 中查询标签

const form = document.querySelector('.form');