如何在不知道元素ID的情况下使其单独替换

How can I make an element replace itself individually without knowing its ID?

本文关键字:情况下 单独 替换 ID 不知道 元素      更新时间:2023-09-26

我第一次写得很糟糕。很抱歉修订:

每个元素都有一个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();
    });
});

更新

根据你修改后的帖子,你可以做以下事情:

演示

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

你只是错过了针对你正在做的元素CCD_ 8可以通过CCD_ 9 靶向来实现

这就是您想要的吗?

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