简体   繁体   English

jQuery选择具有相同名称的子级

[英]JQuery selecting children with same names

I have a list that is being fed in to my page using an ASP.NET repeaters. 我有一个使用ASP.NET中继器输入到我的页面的列表。 The repeater contains a div (divContainer) with two divs (divTitle and divDetails) inside it. 中继器包含一个div(divContainer),其中包含两个div(divTitle和divDetails)。 I'm hiding the divDetails and only want to show it if the user click on divTitle. 我隐藏了divDetails,只想在用户单击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. 当我在第一个divContainer中使用时,此方法对我来说很好,但随后生成的所有后续代码均不起作用,或会在第一个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. 我假设这是因为转发器生成的所有元素都具有相同的ID,因此它选择了第一个。 I probably need to look for child elements only or something like that but am struggling to get it working. 我可能只需要查找子元素或类似的元素,但正在努力使其起作用。

Here's the HTML: 这是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? 当单击具有相同divContainer的divTitle时,JQuery脚本将显示正确的divDetails是什么?

Thanks for your help. 谢谢你的帮助。

Give them classes (IDs have to be unique...the root of your issue), like this: 为他们提供类(ID必须是唯一的...问题的根源),如下所示:

<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: 然后找到相对的元件,通过.find().children()在这种情况下:

$(".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. 在这里,我翻转它打开/关闭,您也可以使用.slideToggle()为动画或只是.show()如果你想它只是显示,不进行切换,能够再次隐藏它。

Demo 演示

http://jsfiddle.net/Sfna4/ 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();
    });  
});
​

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

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