gpt4 book ai didi

javascript - 如何在不知道元素 ID 的情况下单独替换元素?

转载 作者:行者123 更新时间:2023-11-30 00:27:05 24 4
gpt4 key购买 nike

我第一次写的很差。对不起。修订:

每个元素都有一个 ID,但我事先不知道它是什么。我需要的是将鼠标悬停在每个 div 上以仅替换其自己的列表项,即。将鼠标悬停在 #1 上会使 #1 .second 替换 #1 .first,但不会使 #2 .second 替换 #2.first

这是影响两个 div 的内容:

<div class="hover" id="1">
<ul>
<li class="first">First</li>
<li class="second">Second</li>
</ul>
</div>

<div class="hover" id="2">
<ul>
<li class="first">First</li>
<li class="second">Second</li>
</ul>
</div>

$(document).ready(function() {
$(".hover").mouseenter(function() {
$(".second").show();
$(".first").hide();
}).mouseleave(function() {
$(".second").hide();
$(".first").show();
});
});

.second {display:none;}

https://jsfiddle.net/L50bm2vp/

最佳答案

试试这个:

定位每个 span1 类并显示/隐藏其下一个 span2

$(document).ready(function() {
$("div .span1").mouseenter(function() {
$(this).hide().next('.span2').show();

}).mouseleave(function() {
$(this).show().next('.span2').hide();
});
});

更新

根据您修改后的帖子,您可以执行以下操作:

DEMO

$(document).ready(function() {
$(".hover").mouseenter(function() {
$(this).find(".second,.first").toggle();
}).mouseleave(function() {
$(this).find(".second,.first").toggle();
});
});

You were just missing to target the element on which you are doing hover which can be done by targeting with $(this)

关于javascript - 如何在不知道元素 ID 的情况下单独替换元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041338/

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