如何更改与许多其他元素共享其类的单击元素的属性

Tro*_*ojo 1 html javascript css jquery

我正在尝试更改我单击的选项的颜色并将其他选项恢复为原始状态。

let options = document.getElementsByClassName('about-me-submenu-option');

let i;
function unselectAll() {
  for (i = 0; i < options.length; i++) {
    options[i].style.backgroundColor = "";
  }
}

options.onclick = function() {
  unselectAll();
  this.style.backgroundColor = "#333";
}
Run Code Online (Sandbox Code Playgroud)
.container {
  background-color: #333;
  padding: 10px;
  margin: 10px;
  width: 150px;
}

.option {
  background-color: #888;
  padding: 10px;
  color: white;
}
.option:hover {
  background-color: #555;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="option">Option</div>
  <div class="option">Option</div>
  <div class="option">Option</div>
  <div class="option">Option</div>
  <div class="option">Option</div>
  <div class="option">Option</div>
  <div class="option">Option</div>
</div>
Run Code Online (Sandbox Code Playgroud)

或者我把它放在一个 jsfiddle 中:https ://jsfiddle.net/ou3sach0/

如何选择被点击的元素?jQuery 是一个更好的工具吗?

Flu*_*ten 5

您正在将onclick点击处理程序添加到元素数组而不是元素本身 - 您需要向每个元素添加一个点击处理程序,如下所示(有关更多信息,请参阅评论):

// 1. Use querySelectorAll to get a NodeList that we can add the listener to
let options = document.querySelectorAll('.option');

// 2. loop through the options and add the event listener to each element
options.forEach(option => {
   option.addEventListener('click', function(){
      unselectAll();
      this.style.backgroundColor = "#333";  /* add colour to clicked element only */
   } );
});
Run Code Online (Sandbox Code Playgroud)

工作示例:

// 1. Use querySelectorAll to get a NodeList that we can add the listener to
let options = document.querySelectorAll('.option');

// 2. loop through the options and add the event listener to each element
options.forEach(option => {
   option.addEventListener('click', function(){
      unselectAll();
      this.style.backgroundColor = "#333";  /* add colour to clicked element only */
   } );
});
Run Code Online (Sandbox Code Playgroud)
let options = document.querySelectorAll('.option');

let i;
function unselectAll() {
    for (i = 0; i < options.length; i++) {
        options[i].style.backgroundColor = "";
    }
}

// loop through the options and add the event listener to each element
options.forEach(option => {
   option.addEventListener('click', function(){
      unselectAll();
      this.style.backgroundColor = "#333";  
   } );
});
Run Code Online (Sandbox Code Playgroud)
.container {
  background-color: #333;
  padding: 10px;
  margin: 10px;
  width: 150px;
}

.option {
  background-color: #888;
  padding: 10px;
  color: white;
}
.option:hover {
  background-color: #555;
}
Run Code Online (Sandbox Code Playgroud)