开发者

Problem using toggle() on hidden DIVs with JQuery

EDIT: the problem was not on hiding them (as I first thought), It was on using the function toggle() on the hidden DIVs , so I changed the Title Question in hope it helps someone with similar problem

I have problems to hide/show DIVs using the toggle() function:

the code I am using:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
<style type="text/css">
div{width:200px;padding:5px;padding-left:30px;border:0 solid #000;border-left-width:1px;border-bottom-width:1px;font-weight:700}
p{color:grey}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#main span").click(function() {
  开发者_如何学Python      $("#" + $(this).parent().attr("id") + " div").toggle("fast");
    });

    $("#main div").hide();

});
</script>
</head>
<body>
<div id="main">
    <span>hider</span>
    <div id="main-child1"><p>content-child1</p></div>
    <div id="main-child2">
        <span>hider</span>
        <div id="ultra-child"><p>content-ultrachild</p></div>
    </div>
    <div id="main-child3"><p>content-child3</p></div>
    <div id="main-child4">
        <span>hider</span>
        <div id="child-child4"><p>content-c4</p></div>

        <div id="main-child5">
            <span>hider</span>
            <div id="child-c5"><p>content-chl5</p></div>
        </div>
    </div>
</div>
</body>
</html>


$(function() {
    $('#main>div').fadeOut('fast');
});
  1. $(function() {}) will make your script start as soon as the page is ready.
  2. $('#main>div') Target all the first level div in #main.
  3. fadeOut make fade the selected Div.


I think your problem is that you are selecting (and therefore showing) ALL divs when you click on a hider. Use the child selector to only open the levels you want:

$("#" + $(this).parent().attr("id") + " > div").toggle("fast");

However, a better solution would be to just toggle the siblings of the hider

$(this).siblings("div").toggle("fast");

Your code to hide the elements works fine.

Demo: http://jsfiddle.net/EppSm/6


Add a trigger for the first element:

$("#main span:first").trigger("click");

http://jsfiddle.net/EppSm/4/


Here you go:

$("#main > div").hide();


use jQuery .find():

$("#main").find("div").hide();


If you mean using toggle() on an element which is inside a hidden DIV, this is a known bug. It is not fixed as far as I can tell (using jquery 1.7.2) according to the documentation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜