未捕获的TypeError:无法读取属性' style'事件处理时未定义的

时间:2017-06-14 20:58:39

标签: javascript html

我在使用javascript时遇到错误: Uncaught TypeError: Cannot read property 'style' of undefined。有人能告诉我为什么会这样吗

此外,还有一个问题。我试图将2个nav元素内联,但它似乎无法正常工作。

如果我遗漏了任何细节,请告诉我

这是我的代码:



var navlistitems = document.getElementsByClassName("nav-list-items");
for (var i = 0; i < navlistitems.length; i++) {
  console.log(i);
  navlistitems[i].addEventListener("mouseover", function() {
    console.log("mouseover");
    navlistitems[i].style.height = "70px";
  });
  navlistitems[i].addEventListener("mouseout", function() {
    navlistitems[i].style.height = "50px";
  });
  navlistitems[i].style.width = (document.body.offsetWidth / navlistitems.length) + "px";
  console.log("hi");
}
&#13;
* {
  margin: 0px;
  padding: 0px;
}

#hic {
  overflow: hidden;
  height: 150px;
}

#nav-list {
  list-style: none;
}

.nav-list-items {
  text-align: center;
  display: inline-block;
  background: black;
  color: white;
  height: 50px;
  font-size: 20px;
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Ojas's Website</title>
</head>

<body>
  <div>
    <div id="hic">
      <img src="binary-012.jpg" id="hi">
    </div>
    <ul id="nav-list">
      <li class="nav-list-items">Home</li>
      <li class="nav-list-items">Videos</li>
    </ul>
  </div>
</body>

</html>
&#13;
&#13;
&#13;

很抱歉,如果这是一个愚蠢的问题,那么当涉及到javascript时,我就是一个菜鸟。

1 个答案:

答案 0 :(得分:1)

使用css选择器会更容易: https://www.w3schools.com/cssref/css_selectors.asp

现在,为什么它不起作用?

这是因为在执行for循环后i计数器已经改变了。要使其工作,您应该在事件处理程序中使用this关键字(指的是正在处理的元素):

&#13;
&#13;
var navlistitems = document.getElementsByClassName("nav-list-items");

for (var i = 0; i < navlistitems.length; i++) {
  console.log(i);

  navlistitems[i].addEventListener("mouseover", function() {
    console.clear();
    console.log(i);
    this.style.height = this.style.lineHeight = "70px";
  });

  navlistitems[i].addEventListener("mouseout", function() {
    console.clear();
    console.log(i);
    this.style.height = this.style.lineHeight = "50px";
  });

  navlistitems[i].style.width = (document.body.offsetWidth / navlistitems.length) + "px";
}
&#13;
* {
  margin: 0px;
  padding: 0px;
}

#nav-list {
  list-style: none;
  display: flex;
}

.nav-list-items {
  text-align: center;
  background: black;
  color: white;
  height: 50px;
  line-height: 50px;
  font-size: 20px;
  border: 1px solid #fff;
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Ojas's Website</title>
</head>

<body>
  <div>
    <ul id="nav-list">
      <li class="nav-list-items">Home</li>
      <li class="nav-list-items">Videos</li>
    </ul>
  </div>
</body>

</html>
&#13;
&#13;
&#13;