gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'style' of undefined when eventhandling

转载 作者:行者123 更新时间:2023-11-28 00:56:30 27 4
gpt4 key购买 nike

我在使用 javascript 时遇到错误:未捕获类型错误:无法读取未定义的属性“style”。谁能告诉我为什么会这样

另外,还有一个问题。我正在尝试使 2 个导航元素内联,但它似乎不起作用。

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

这是我的代码:

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");
}
* {
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;
}
<!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>

抱歉,如果这是一个愚蠢的问题,我对 javascript 是个菜鸟。

最佳答案

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

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

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

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";
}
* {
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;
}
<!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>

关于javascript - 未捕获的类型错误 : Cannot read property 'style' of undefined when eventhandling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44554631/

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