简体   繁体   中英

Trying to toggle visibility of a dd element

I'm trying to toggle the visibility of my dd element. For example, if I click one dt, it will show the dd. Then, if click the next dt, the last dd should hide and the current dd should show. Right now, I have to click on the same dt to show and hide it.

Here's the section of the html code:

<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. By first finding the sibling dd element, we can exclude that from adding the hide class using .not ; and then we can toggle the hide class on that element:

 $('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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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