简体   繁体   English

State 依赖于手风琴上的 class 名称

[英]State dependent class names on accordion

So I have this problem that I guess is a walk in the park to fix.所以我有这个问题,我想是在公园里散步来解决。

I'm using the JS snippet below on a website I'm building and what the snippet does is it creates accordions for some HTML elements where the class .bapf_head is the header (control) of the accordion and the .bapf_body is the expand/collapse. I'm using the JS snippet below on a website I'm building and what the snippet does is it creates accordions for some HTML elements where the class .bapf_head is the header (control) of the accordion and the .bapf_body is the expand/坍塌。

I wrote the if logic where the function checks if the .bapf_body is opened or not and will then add or remove a class to the .bapf_head depending on the state.我编写了if逻辑,其中 function 检查.bapf_body是否打开,然后根据 Z9ED39E2EA931586B57A985A694E2 将.bapf_head添加或删除到 .bapf_head 中。 This then results in a +/- symbol that indicates open/close depending on the state.这会产生一个 +/- 符号,表示打开/关闭取决于 state。

So the problem is that I have multiple Div's that uses the same class names and all of them gets updated with the .open class name when one of the accordions are opened or closed.所以问题是我有多个使用相同 class 名称的 Div,并且当其中一个手风琴打开或关闭时,所有这些都使用.open class 名称进行更新。 So let's say I have three accordions and I open one of them, then all three gets the class .open added and hence all gets the '-' symbol even though only one accordion is open.因此,假设我有三个手风琴,我打开其中一个,然后三个手风琴都添加了 class .open ,因此即使只有一个手风琴打开,所有手风琴都得到“-”符号。

Anyone knows how to make sure only the clicked accordion gets the updated class-name rather then all of the accordions at the same time?任何人都知道如何确保只有点击的手风琴获得更新的类名,而不是同时获得所有的手风琴?

Code below;代码如下;

jQuery(document).ready(function($) {
    $(".bapf_head").click(function () {
        $header = $(this);
        $content = $header.next();
        $content.slideToggle(300, function () {
            $header.text(function () {
                if ($content.is(":visible")) {
                    $(".bapf_head").addClass("open");
                } else {
                    $(".bapf_head").removeClass("open");
                };          
            });
        });
    });
});
     if ($content.is(":visible")) {
         $(this).addClass("open");
     } else {
         $(this).removeClass("open");
     };  

you need to reference the event-related DOM element, not select all the ones with that class您需要引用与事件相关的 DOM 元素,而不是 select 与 class 的所有元素

also, .click() is long deprecated afaik, you should use .on('click', ...此外, .click()已被长期弃用 afaik,您应该使用.on('click', ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM