gpt4 book ai didi

jQuery 目标与鼠标悬停时的类相同的 id

转载 作者:行者123 更新时间:2023-12-01 07:11:23 26 4
gpt4 key购买 nike

当鼠标悬停在 #photo-menu li 上时,我尝试将事件类添加到 #photo-desc li。

$('#photo-menu li').on('mouseenter mouseleave', function(){
var pClass = this.className;
var pId = ('#photo-desc li').id;
if (pClass == pId) {$('#photo-desc li').addClass('active');}
});

<ul id="photo-menu">
<li class="photo-1"><a href="">Photo 1</a></li>
<li class="photo-2"><a href="">Photo 2</a></li>
<li class="photo-3"><a href="">Photo 3</a></li>
<li class="photo-4"><a href="">Photo 4</a></li>
</ul>

<ul id="photo-desc">
<li id="photo-1">Photo 1</li>
<li id="photo-2">Photo 2</li>
<li id="photo-3">Photo 3</li>
<li id="photo-4">Photo 4</li>
</ul>

最佳答案

在您的示例中,您的类与第二个类中的 id 具有相同的名称。所以非常简单:

$('#photo-menu li').on('mouseenter mouseleave', function (e) {
var curClass = $(this).attr("class"); //take class
if (e.type == "mouseenter") {
$("#" + curClass).addClass("active"); //use class name to get the id in second list
} else {
$("#" + curClass).removeClass("active");
}
});
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="photo-menu">
<li class="photo-1"><a href="">Photo 1</a>

</li>
<li class="photo-2"><a href="">Photo 2</a>

</li>
<li class="photo-3"><a href="">Photo 3</a>

</li>
<li class="photo-4"><a href="">Photo 4</a>

</li>
</ul>
<ul id="photo-desc">
<li id="photo-1">Photo 1</li>
<li id="photo-2">Photo 2</li>
<li id="photo-3">Photo 3</li>
<li id="photo-4">Photo 4</li>
</ul>

关于jQuery 目标与鼠标悬停时的类相同的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26466227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com