jQuery toggle dynamically

99封情书 提交于 2019-12-11 13:58:22

问题


I want to toggle divs dynamically. Here is what I found so far...

$(".toggle").click(function() { 
$(this).next('.container').toggle('fast'); 
});

What I have is this (HTML):

<h4 class="toggle">1</h4>
<h4 class="toggle">2</h4>
<h4 class="toggle">3</h4>
<div class="container">Content1</div>
<div class="container">Content2</div>
<div class="container">Content3</div>

When I click the FIRST element (h4 with class toggle) I want the FIRST element with class container to open / close.

When I click the second toggle-class the second container-class should open.

The next in my example don't work.


回答1:


If you need/want to keep this DOM structure, you should use the index.

$('.toggle').click(function() {
    $('.container').eq($(this).index()).toggle('fast');
});

Ref.: .eq(), .index()

Example: http://www.jsfiddle.net/4yUqL/36/




回答2:


I think what you are looking for is

$(".toggle").click(function() { 
    $($('.container')[$(this).index(".toggle")]).toggle('fast'); 
});

Working fiddle




回答3:


You may try out the toggle feature of JQuery. And I will rather have some other dependency between the headers and the content divs, rather than trusting the order of their occurrence.




回答4:


if you change the order of your html:

<h4 class="toggle">1</h4>
<div class="container">Content1</div>
<h4 class="toggle">2</h4>
<div class="container">Content2</div>
<h4 class="toggle">3</h4>
<div class="container">Content3</div>

your code works, because it's just getting the next DOM element and toggling it if it matches the class. However it's pretty shaky and other people's examples that tell js more specifically what to do would be better.



来源:https://stackoverflow.com/questions/4593953/jquery-toggle-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!