使用 select 列表对项目列表进行排序的正确方法是什么

what is the correct way to sort list of items by using a select list

假设我有一个这样的排序列表

.dropbtn {
  background-color: #04AA6D;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.dropdown:hover .dropdown-content {
  display: block;
}

.dropdown:hover .dropbtn {
  background-color: #3e8e41;
}
<div class="dropdown">
              <button class="dropSortbtn2"> Food <i class="bi bi-caret-down"></i></button>
              <div class="dropdown-content">
                <a href="#">Tomato</a>
                <a href="#">APPle</a>
                <a href="#">Carrot</a>
                <a href="#">Broccoli</a>
              </div>
            </div>

我希望下拉列表能够对项目列表进行排序并隐藏其他项目,

例如,如果我有这个列表

<ul>
  <li>Tomato</li>
  <li>APPle</li>
  <li>Broccoli</li>
  <li>Carrot</li>
  <li>Tomato</li>
  <li>Broccoli</li>
</ul>

并且用户在下拉列表中单击番茄,所有项目都应该被隐藏,并且只会显示番茄元素。这样做的正确方法是什么?知道排序下拉列表会很长

您可以向所有 select 选项添加一个 click 事件侦听器,循环遍历 ul 中的每个 li 并隐藏那些 textContent 是不等于 select 选项的 textContent 单击。

const options = document.querySelectorAll('.dropdown .dropdown-content a')
const listItems = document.querySelectorAll('#list li');

options.forEach(f => f.addEventListener('click', function(e){
  let text = this.textContent;
  listItems.forEach(e => e.style.display = e.textContent == text ? "block" : "none")
}))
.dropbtn {
  background-color: #04AA6D;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.dropdown:hover .dropdown-content {
  display: block;
}

.dropdown:hover .dropbtn {
  background-color: #3e8e41;
}
<div class="dropdown">
  <button class="dropSortbtn2"> Food <i class="bi bi-caret-down"></i></button>
  <div class="dropdown-content">
    <a href="#">Tomato</a>
    <a href="#">APPle</a>
    <a href="#">Carrot</a>
    <a href="#">Broccoli</a>
  </div>
</div>

<ul id="list">
  <li>Tomato</li>
  <li>APPle</li>
  <li>Broccoli</li>
  <li>Carrot</li>
  <li>Tomato</li>
  <li>Broccoli</li>
</ul>