简体   繁体   中英

JQuery selecting children with same names

I have a list that is being fed in to my page using an ASP.NET repeaters. The repeater contains a div (divContainer) with two divs (divTitle and divDetails) inside it. I'm hiding the divDetails and only want to show it if the user click on divTitle.

This works fine for me when in the first divContainer but all subsequent ones that get generated do not work or will slide down the first divDetails. I'm assuming this is because all the elements that get generated by the repeater have the same ID so it selects the first one. I probably need to look for child elements only or something like that but am struggling to get it working.

Here's the HTML:

<div id="divContainer">
    <div id="divTitle">Foo</div>
    <div id="divDetails" class="display:none">Foo details</div>
</div>

<div id="divContainer">
    <div id="divTitle">Foo</div>
    <div id="divDetails" class="display:none">Foo details</div>
</div>

What would the JQuery script be to show the correct divDetails when divTitle withing the same divContainer is clicked?

Thanks for your help.

Give them classes (IDs have to be unique...the root of your issue), like this:

<div class="divContainer">
    <div class="divTitle">Foo</div>
    <div class="divDetails" style="display:none">Foo details</div>
</div>

Then find the element relatively, via .find() or .children() in this case:

$(".divContainer").click(function() {
  $(this).find(".divDetails").toggle();
});

Here I'm toggling it open/closed, you could also use .slideToggle() for an animation or just .show() if you want it shown only, not toggle-able to hide it again.

Demo

http://jsfiddle.net/Sfna4/

<div class="divContainer">
    <div class="divTitle">Moo</div>
    <div class="divDetails" style="display:none">Moo details</div>
</div>

<div class="divContainer">
    <div class="divTitle">Foo</div>
    <div class="divDetails" style="display:none">Foo details</div>
</div>
​


jQuery(function(){
    jQuery('.divTitle').bind('click',function(){
                  jQuery(this).siblings('.divDetails').slideToggle();
    });  
});
​

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