gpt4 book ai didi

javascript - dom 操作/事件处理程序没有工作

转载 作者:行者123 更新时间:2023-11-30 20:36:28 25 4
gpt4 key购买 nike

我还在学习这个 dom 操作,所以我试着让我的按钮在你悬停它时有一个阴影。

这是html代码

<nav class="navbar navbar-expand-sm fixed-top" id="myNavbar">
<div class="navbar-header">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupported" aria-controls="navbarSupported" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<a href="#" class="navbar-brand" id="hello">Navbar</a>
<!-- Nav content -->
<div class="collapse navbar-collapse" id="navbarSupport">
<ul class="nav navbar-nav navbar-left">
<li class="nav-item">
<a href="#" class="nav-link active">Home</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">About</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">Inspiration</a>
</li>
</ul>
<ul class="nav navbar-nav ml-auto navbar-right">
<li class="nav-item">
<a href="#" class="nav-link">Create</a>
</li>
</ul>
</div>
</nav>

我在这里测试了 dom 操作是否有效,所以我尝试单击我的导航栏来测试它,但我的控制台中没有显示任何内容,但没有任何错误。

`const btn = document.getElementById('myNavbar');

btn.addEventListener('onclick', () => { 控制台日志(123);});`

最佳答案

事件的名称是click,而不是onclick。在分配给元素的属性时使用onclick(通常应该尽量避免),例如

btn.onclick = () => console.log('foo');

但在添加监听器时使用'click' string

const btn = document.getElementById('myNavbar');
btn.addEventListener('click', () => { console.log(123); });
<nav class="navbar navbar-expand-sm fixed-top" id="myNavbar">
<div class="navbar-header">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupported" aria-controls="navbarSupported" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<a href="#" class="navbar-brand" id="hello">Navbar</a>
<!-- Nav content -->
<div class="collapse navbar-collapse" id="navbarSupport">
<ul class="nav navbar-nav navbar-left">
<li class="nav-item">
<a href="#" class="nav-link active">Home</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">About</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">Inspiration</a>
</li>
</ul>
<ul class="nav navbar-nav ml-auto navbar-right">
<li class="nav-item">
<a href="#" class="nav-link">Create</a>
</li>
</ul>
</div>
</nav>

关于javascript - dom 操作/事件处理程序没有工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49788335/

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