下拉菜单通过JQuery动态切换类

问题描述 投票:0回答:1

我有这种情况:在this页面,有一些艺术家有一些纹身风格。我的想法是为每个艺术家分配一个类,例如,样式的名称,创建一个带有各种样式名称的下拉菜单,并确保在单击各个项目时,通过JQuery,分配的类用另一个“突出显示”具有该特定样式的所有艺术家(例如,图像周围带有红色边框)进行修改。

你能帮助我创造一个类似的情况吗?你能给我一些想法吗?我已经疯了一个星期了!

谢谢你的建议!

jquery
1个回答
0
投票

使用适当的类标记照片后,您可以将回调绑定到下拉列表更改事件以重置所有先前的高亮显示,然后根据特定类将突出显示类提供给所需的子选择。

我想通过一个例子会更清楚:

// Dynamically build select options
let tatoos = [];

$('.tatoo').each(function(i, t) {
  let tatoo = t.className.replace('tatoo ', '');
  
  if(tatoos.indexOf(tatoo) < 0) tatoos.push(tatoo);
});

// Add options to the dropdown list
tatoos.sort().forEach(function(tatoo) {
  $('#tatoos').append(`<option value="${tatoo}">${tatoo}</option>`);
});

// Bind change event to monitor dropdown selection
$('#tatoos').change(function(ev) {
  let c = $(this).val();
  
  $('.tatoo').removeClass('highlight');
  if(c) {
    $('.' + c).addClass('highlight');
  }
});
.tatoo {
  display: inline-block;
  margin: 10px;
  width: 50px;
  height: 50px;
  background-color: #999
}

.tatoo.highlight {
  border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="tatoos"><option value=""></option></select>
<div>
<div class="tatoo tatoo1">1</div>
<div class="tatoo tatoo1">1</div>
<div class="tatoo tatoo2">2</div>
<div class="tatoo tatoo1">1</div>
<div class="tatoo tatoo3">3</div>
<div class="tatoo tatoo2">2</div>
<div class="tatoo tatoo3">3</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.