切换div旁边的元素

时间:2011-07-30 02:17:31

标签: jquery toggle

下面的元素第二个隐藏按钮正在工作。如果我把div放在按钮上它不起作用。如果没有给出id可以这样做吗?

的JavaScript

$(document).ready(function(){
$(".toggle").click(function() 
{  
// hides matched elements if shown, shows if hidden 
$(".content", $(this).next()).toggle(); 
});   
});

HTML

<div>
<input class="toggle" type='button' value='hide'>
</div>
<div>
<div class="content">
Content 1
</div>
</div>
<br><br>
<input class="toggle" type='button' value='hide'>
<div>
<div class="content">
Content 2
</div>
</div>

3 个答案:

答案 0 :(得分:0)

我认为这就是你的意思:

$(".toggle").click(function() {
    $(this).parent().next().find(".content").toggle();
});

//或

$(".toggle").click(function() {
    $(".content", $(this).parent().next()).toggle();
});

换句话说,您需要在使用.next()获取下一个div之前遍历一个级别。

演示:http://jsfiddle.net/HX6Kv/

答案 1 :(得分:0)

试试这个

$(document).ready(function(){
$(".toggle").click(function() 
{  
// hides matched elements if shown, shows if hidden 
      $(this).parent().next("div.content").toggle(); 
});   
});

答案 2 :(得分:0)

$(document).ready(function() {
    $(".toggle").click(function() {  
        // hides matched elements if shown, shows if hidden 
        $(this).parents().find(".content").toggle(); 
    });   
});

我尝试了上面的内容,当我为内容div设置主要div时,它也适用于我