代码之家  ›  专栏  ›  技术社区  ›  omega1

jQuery多个显示/隐藏div问题

  •  1
  • omega1  · 技术社区  · 6 年前

    我有一个问题,其中有一些代码的多个实例,我正在使用显示/隐藏div。问题是,如果我单击其中一个按钮,所有的div都会显示出来,但我不知道为什么会出现这种情况,因为div有不同的类。

    我的意图是,在这个示例中,当页面加载时,它显示 <div class="red-top1> <div class="red-top2> 当我按下按钮mybuttonop1显示 <div class="green-top1> 但它却显示了两者 <div class=“green-top1> <div class="green-top2">

    谢谢。

    以下是相关代码:

    function ButtonTextTop2() {
        if ($("#green-top2").is(":visible")) {
            $("button").text("Show less...");
        } else {
            $("button").text("Show more...");
        }
    }
    ButtonTextTop2();
    $("button").click(function () {
        $("#green-top2").toggle();
        $("#red-top2").toggle();
        ButtonTextTop2();
    });
    
    function ButtonTextTop1() {
        if ($("#green-top1").is(":visible")) {
            $("button").text("Show less...");
        } else {
            $("button").text("Show more...");
        }
    }
    ButtonTextTop1();
    $("button").click(function () {
        $("#green-top1").toggle();
        $("#red-top1").toggle();
        ButtonTextTop1();
    });
    #red-top1 {
    }
    #green-top1 {
        display:none;
    }
    #red-top2 {
    }
    #green-top2 {
        display:none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="red-top1">
        Code here
    </div>
    <div class="green-top1">
        Other code here
    </div>
    
    <div class="red-top2">
        Code here
    </div>
    <div class="green-top2">
        Other code here
    </div>
    
    <button class="mybuttontop1">Show more...</button>
    <script type="text/javascript">
    
    </script>
    
    
    <button class="mybuttontop2">Show more...</button>
    2 回复  |  直到 6 年前
        1
  •  2
  •   Community leo1    4 年前

    Selectors 都错了。您正在尝试访问 Style Class 选择器 (.) 但是使用 Element Id 选择器 (#)

    只要更改所有脚本代码和样式代码中的“#”,就可以开始了。

    例如:

    Javascript语言

    用途: if ($(".green-top1").is(":visible")) {

    if ($("#green-top1").is(":visible")) {

    风格

    用途: .green-top1 {

    #green-top1 {

    这是您的工作代码: https://jsfiddle.net/12toxyn9/

    用正确的代码更新答案: https://jsfiddle.net/2p90cehb/

    用途: $(".mybuttontop1").click(function () { $(".mybuttontop2").click(function () {

    而不是: $("button").click(function () { 对于这两种功能。

        2
  •  1
  •   Edward Perpich    6 年前

    $("#green-top") ,而不是类标记选择器 $(".green-top") .

    这也适用于CSS。你不是在定义类,而是在定义ID的样式。定义 class 绿顶,你会的

        .green-top {
            style: here;
        }
    

    我肯定这是造成你所看到的不一致的原因。