如何修复“无法读取null的属性'addEventListener'”

时间:2019-10-09 10:58:02

标签: javascript html

我正在从视频教程中学习如何制作自动完成搜索栏。我做了视频所做的一切,但无济于事。我认为问题在于add.EventListener。当我在Chrome中运行代码时,在控制台中显示:

  

未捕获的TypeError:无法读取null的属性'addEventListener'

代码:

searchInput.addEventListener('keyup', function() {
const input = searchInput.value;
suggestionsPanel.innerHTML = '';
const suggestions = movies.filter(function(movie) {
  return movie.name.toUpperCase().startsWith(input);
});
suggestions.forEach(function(suggested){
  const div = document.createElement('div');
  div.innerHTML = suggested;
  suggestionsPanel.appendChild(div);
});
if (input=== ''){
  suggestionsPanel='';
} })

这是JavaScript代码,下面是HTML代码,以查看任何错误。

<html>
<head>
    <link rel="icon" href="Geofflixlogo.png">
    <title>Geofflix</title>
    <link rel="stylesheet" href="geofflix.css">
    <script src="geofflix.js" type="text/javascript"></script>
</head>

<body>
    <div class="header">
        <div class="logo">
            <a href="index.html">
            <img src="Logo.png" height="50">
            </a>
        <div class="navi">
            Watch what everyone's talking about. For Free!        
        </div>
        <div class="searchbar">
                <input class="search-input" type="text" placeholder="Search...">
                <div class="suggestions">
                </div>                
        </div>      
        <div class="nav">
                <a href="index.html">Home</a>
                <a href="Movies.html">Movies</a>
          </div>
        </div>
    </div>
 </body>

1 个答案:

答案 0 :(得分:0)

我不知道您的错误来自哪里,但是看我的函数似乎还可以。

createvalueifdoesntexist

工作的小提琴:https://jsfiddle.net/70ynvh4r/1/