我尝试检查当前悬停的元素并向具有相同数据值的 div 添加类
<a data-toggle="tooltip" title="Złącze słuchawkowe" data-id="#dialog1"
class="single-image-item single-image-item-1" href="#" data-value="Headphones Plug">
<i>1</i>
</a>
<a data-toggle="tooltip" title="Złącze słuchawkowe" data-id="#dialog2"
class="single-image-item single-image-item-1" href="#" data-value="Charging Port">
<i>1</i>
</a>
<div class="single-hot-spot-item" data-value="Headphones Plug">
<span class="hot-spot-single-item hot-spot-item-1">1 </span>
<p class="hot-spot-item-description">Złącze słuchawkowe</p>
</div>
<div class="single-hot-spot-item" data-value="Charging Port">
<span class="hot-spot-single-item hot-spot-item-1">1 </span>
<p class="hot-spot-item-description">Złącze słuchawkowe</p>
</div>
最好的方法是什么?
最佳答案
您可能想保留您的 <div>
由 data-value 属性索引,然后使用 jQuery.hover(fn)
切换。
(function($) {
// building this can be one-liner, but lazy
sections = {}
$('div').each(function() {
sections[$(this).data('value')] = this;
});
$('a').hover(function(event) {
const section = sections[$(this).data('value')];
$(section).toggleClass('hover', event.type == 'mouseenter');
});
}(jQuery));
.hover {
background-color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-toggle="tooltip" title="Złącze słuchawkowe" data-id="#dialog1"
class="single-image-item single-image-item-1" href="#" data-value="Headphones Plug">
<i>1</i>
</a>
<a data-toggle="tooltip" title="Złącze słuchawkowe" data-id="#dialog2"
class="single-image-item single-image-item-1" href="#" data-value="Charging Port">
<i>1</i>
</a>
<div class="single-hot-spot-item" data-value="Headphones Plug">
<span class="hot-spot-single-item hot-spot-item-1">1 </span>
<p class="hot-spot-item-description">Złącze słuchawkowe</p>
</div>
<div class="single-hot-spot-item" data-value="Charging Port">
<span class="hot-spot-single-item hot-spot-item-1">1 </span>
<p class="hot-spot-item-description">Złącze słuchawkowe</p>
</div>
关于jquery - 检查、比较数据值并添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60720011/