开发者

hiding inner tables with JQuery

开发者 https://www.devze.com 2023-02-08 18:13 出处:网络
I\'m trying to hide an inner table with JQuery where theelement that triggers the hiding is in the parent table. Here\'s my code:

I'm trying to hide an inner table with JQuery where the element that triggers the hiding is in the parent table. Here's my code:

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
    $(".collapsible").click(function(event) {

        event.preventDefault();

        inner = $(this).find(".inner");



        if($(inner).is(":visible") == true) {

            alert("hiding");

            $(inner).hide("slow");

        }

        else {

            alert("showing");

            $(inner).show("slow");

        }

    });

    $(".inner").each(function(index, element) {

        $(this).hide(0);

    });
});
</script>

<table class='outer'>
<tr><td><a class='collapsible' href='#'>click here</a></td></tr>
<tr><table class='inner'>
<tr><td>thing</td></tr><tr><td>another thing</td></tr>
</table>
</table>
<table class='outer'>
<tr><td><a class='collapsible' href='#'>click here</a></td></tr>
<开发者_如何学Ctr><table class='inner'>
<tr><td>something else</td></tr><tr><td>another something else</td></tr>
</table>
</table>
</body>
</html>

Does anybody know why clicking on "click here" not make the inner table show? Thanks in advance


Because .find() is looking within the .collapsible anchor. You need to step up to the parent table first to use .find() correctly:

$(this).closest("table.outer").find("table.inner");

Your whole code can be simplified to:

$(function() {
    $(".collapsible").click(function(event) {
        event.preventDefault();
        $(this).closest("table.outer").find("table.inner").toggle('slow');
    });

    $(".inner").hide();
});
0

精彩评论

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