简体   繁体   English

试图切换 dd 元素的可见性

[英]Trying to toggle visibility of a dd element

I'm trying to toggle the visibility of my dd element.我正在尝试切换 dd 元素的可见性。 For example, if I click one dt, it will show the dd.例如,如果我单击一个 dt,它将显示 dd。 Then, if click the next dt, the last dd should hide and the current dd should show.然后,如果单击下一个 dt,最后一个 dd 应该隐藏并且当前 dd 应该显示。 Right now, I have to click on the same dt to show and hide it.现在,我必须点击同一个 dt 来显示和隐藏它。

Here's the section of the html code:这是 html 代码的部分:

<template id="todo">
    <div class="todo-item">
        <dt class="todo-id"></dt>
        <dt  class="todo-title"></dt>
        <dd class="todo-description hide"></dd>
    </div>
</template>

and here's the listener handling it:这是处理它的听众:

 $('body').on('click', '.todo-item dt', function (e) {
    $(this).siblings().closest('.todo-description').toggleClass('hide');     
});

To make the other descriptions disappear, you need to add the hide class to them when you click on a dt element.要使其他描述消失,您需要在单击dt元素时将hide class 添加到它们。 By first finding the sibling dd element, we can exclude that from adding the hide class using .not ;通过首先找到兄弟dd元素,我们可以将其排除在使用.not添加hide class 之外; and then we can toggle the hide class on that element:然后我们可以在该元素上切换hide class :

 $('body').on('click', '.todo-item dt', function(e) { let descr = $(this).siblings('.todo-description'); $('.todo-description').not(descr).addClass('hide'); descr.toggleClass('hide'); });
 .hide { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="todo"> <div class="todo-item"> <dt class="todo-id">item #1 id</dt> <dt class="todo-title">item #1 title</dt> <dd class="todo-description hide">item #1 description</dd> </div> <div class="todo-item"> <dt class="todo-id">item #2 id</dt> <dt class="todo-title">item #2 title</dt> <dd class="todo-description hide">item #2 description</dd> </div> </div>

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

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