开发者

jQuery selectors?

Using jQuery I am trying to create a function to show and hide the DIV below the table/tr that has been clicked, but when I click in one, all the DIVs will slide up, also slide down it is not working.

I tried if开发者_如何学JAVA ($(".container:first").is("hidden")) but I guess is not the first element under element clicked but first element on the document.

How do I get this working?

Based on the following example.

<html>
    <head>
        <script type="text/javascript" src="jquery-1.4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $(".header").click(function(){
                    if ($(".container").is("hidden")){
                           $(".container").slideUp("slow");
                    } else {
                       $(".container").slideDown("slow");
                    }
                });
            });
        </script>
    </head>

    <body>
        <table class="header">
            <tr><td>Row1</td></tr>
        </table>
        <div class="container">Container 1</div>

        <table class="header">
           <tr><td>Row2</td></tr>
        </table>
        <div class="container">Container 2</div>
    </body>
</html>


You want to get only the next container, so you'd use $.next():

$(".header").click(function(){
  $(this).next(".container").slideToggle();
});

Online Demo: http://jsbin.com/eyuwi3/edit

Updated

Requested in the comments was to make this "work on the tr elements." If you click anywhere within the table, the table's click event will eventually fire - unless a child is stopping the propagation.

If this code is not working, then your problem is elsewhere. Make sure you don't have elements between your table and your .container element. $.next() only selects immediate siblings, which is what your sample-code suggests you have.

If problems persist, you could try the following:

$(".header").click(function(){
  $(this).nextAll(".container:first").slideToggle();
});

Online Demo: http://jsbin.com/eyuwi3/2/edit


Your jQuery selector are finding all .container divs in the document in the click handler. Instead, use the fact that, in event handlers, this is set to the current event target:

$(document).ready(function() {
    $(".header").click(function() {
        $(this).next('div.container').slideToggle("slow");
    });
});


I think, though I've not checked, that:

$(this).next('div.container');

should work to select the element; though Jonathan's answer is the more complete.


Edited in response to comments made to Jonathan's answer:

That is cool, thanks for the answer, could you also let me know how to apply to the tr element inside of the table with class "header"?

It depends on where the click's being detected, but assuming the click event is taken by the table cell:

$(this).prev('tr#header');

should select the #header table row.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜