如何将事件添加到节点列表对象

时间:2019-03-06 06:59:45

标签: javascript html events onclick

好吧,所以我尝试使用一种addEventListener方法来单击event,这将切换一个类以使我的菜单栏动画化并显示一个侧面菜单。这是我的代码

//reference to the ".menu" class
const menu = document.querySelector('.menu');
console.log(menu)

const menuButton = document.querySelector('.menu-button')
// Using your menuButton reference, add a click handler that calls toggleMenu
console.log(menuButton);
menuButton.addEventListener("click", function() {
  menuButton.classList.toggle('.menu--open');
  console.log('toggled');
});
<div class="header">
  <img class="menu-button" src="./assets/menu.png" />
  <h1>Lambda School Newsfeed</h1>
</div>
<div class="menu">
  <ul>
    <li>Students</li>
    <li>Faculty</li>
    <li>What's New</li>
    <li>Tech Trends</li>
    <li>Music</li>
    <li>Log Out</li>
  </ul>
</div>

我得到了一个返回的节点列表,并且不允许我使用事件方法,但是我似乎无法解决问题

2 个答案:

答案 0 :(得分:0)

在此代码段.中从.menu--open中删除menuButton.classList.toggle('.menu--open');

//reference to the ".menu" class
const menu = document.querySelector('.menu');
console.log(menu)

const menuButton = document.querySelector('.menu-button')
// Using your menuButton reference, add a click handler that calls toggleMenu
console.log(menuButton);
menuButton.addEventListener("click", function() {
  menuButton.classList.toggle('menu--open');
});
.menu--open {
  border: 1px solid red;
}

.header {
  cursor: pointer;
}
<div class="header">
  <img class="menu-button" src="./assets/menu.png" />
  <h1>Lambda School Newsfeed</h1>
</div>
<div class="menu">
  <ul>
    <li>Students</li>
    <li>Faculty</li>
    <li>What's New</li>
    <li>Tech Trends</li>
    <li>Music</li>
    <li>Log Out</li>
  </ul>
</div>

答案 1 :(得分:0)

您的代码中有两个问题:

  1. 您需要在班级列表切换功能内使用menu--open而不是.menu--open
  2. 您需要使用menu.classList.toggle而不是menuButton.classList.toggle

//reference to the ".menu" class
const menu = document.querySelector('.menu');
console.log(menu)

const menuButton = document.querySelector('.menu-button')
// Using your menuButton reference, add a click handler that calls toggleMenu
console.log(menuButton);
menuButton.addEventListener("click", function() {
  menu.classList.toggle('menu-open');
});
.menu.menu-open {
  display: none;
}
<div class="header">
  <img class="menu-button" src="./assets/menu.png" />
  <h1>Lambda School Newsfeed</h1>
</div>
<div class="menu">
  <ul>
    <li>Students</li>
    <li>Faculty</li>
    <li>What's New</li>
    <li>Tech Trends</li>
    <li>Music</li>
    <li>Log Out</li>
  </ul>
</div>