为什么这个 jQuery 显示和隐藏脚本没有按预期工作?

Why is this jQuery show & hide script not working as expected?

我对编码很陌生,我有点被困在我正在尝试制作的 手风琴式设备 上。

想法是有 4 个 div 元素,在它们下面还有另一个 div。当点击4个div中的一个时,相应的文本将显示在框中;单击另一个,第一个 div 的文本消失并变为另一个。单击相同,框就消失了。

我的游戏计划:将相同的 class 分配给所有应该隐藏的元素,并在站点启动时隐藏它们;单击 div 时,仅显示具有相应 ID 的元素。

目前,即使只有一个 div,我也无法让它正常工作,但我不知道为什么。如果您能告诉我问题出在哪里,我将不胜感激。

到目前为止我的代码(现在只有 2 div 秒,以减少混乱):

HTML:

<div class="expander" id="first-p">Click this text to see the one below.</div>
<div class="expander" id="second-p">Another clickable div.</div>
<div class="concealed" id="concealed-first-p">This is the hidden text.</div>
<div class="concealed" id="concealed-second-p">This is another hidden text.</div>

JQUERY:

$(document).ready(function() {
    $(".concealed").hide();             //hide all elements with class .concealed after site launch

    $(".expander").click(function(){             //A div which triggers the displaying of the hidden stuff is clicked


/* If the hidden div is already displayed, hide it instead and call it a day */

            if (clickedElement == $(this).attr("id")) {
                alert ("hide div again");
                $("#expandingElement").hide(); 
            }

/* Show the hidden div */

else {
            $("#expandingElement").hide();             // hide any div that might already be displayed
            var clickedElement = $(this).attr("id");            // get the ID of the clicked element so we know which correlating one to display afterwards
            var expandingElement = "concealed-" + clickedElement;            // construct the ID of the element to display
            alert("Name of expandingElement ID is " + expandingElement);             // this is just an alert so I know the variable was constructed correctly
            $("#expandingElement").show();             // show the div
            }
        });
    });

到目前为止,代码一直运行到警报显示正确的变量名称为止,但之后 div 没有出现。你能告诉我我做错了什么吗?

另外,我想有更简单的方法可以做到这一点,我很乐意就此事提供任何帮助。但最重要的是,我想了解为什么代码没有按预期工作。

看来你搞砸了选择器:

None 您的 div 具有 ID "expandingElement" 但您调用

$("#expandingElement").hide()

这会尝试将 hide() 应用于 ID 为 expandingElement 的元素。但是您想使用名为 expandingElement 的变量。所以你需要做的是正确地连接这两个:

$("#"+expandingElement).hide()

您正在“”中使用您的ID。所以它被视为string。 你应该像这样使用:

$("#" + expandingElement).show();

如果我没看错的话,您似乎在寻找类似于 Boostrap's Tabs

的内容

你的失败是: $("#expandingElement").show()/hide();

解决方案: $("#"+expandingElement).show()/hide();

expandingElement 是一个变量,所以如果你把它插入到 btwn '' 它就变成了一个字符串。

无论如何:

$(document).ready(function() {
    $(".concealed").hide();       

    $(".expander").click(function(){            
       $(".concealed").hide();
       var clickedElement = $(this).attr("id");   

       var expandingElement = "concealed-" + clickedElement;            

       $("#"+expandingElement).show();    

        });
    });