using jQuery toggle function on a table row makes table itself grow

江枫思渺然 提交于 2019-12-08 08:12:12

问题


I'm using the jQuery toggle effect hooked to the click() event of 1 table row to toggle the visibility of the next row (which also happens to be the final row in the table). If I click the firing row multiple times in succession, the table that contains the 2 rows grows a little every time the toggling row shows.

Here's the jQuery I'm using:

$(document).ready(function() {
    $(".sectionhead").click( function() {
        $(this).next("tr").toggle("150");
    });
});

So after a few iterations, the table (which has only the tr.sectionhead row visible in it) is quite large.

Is there a built-in way that I can avoid this behaviour, or is there some way of doing this in jQuery that would be easier than what I'm doing?

Edit

My actual solution suggested by ScottE's answer below (I don't want to have to class the tr I'm toggling, and it will be visible to start with):

$(document).ready(function() {
    $(".sectionhead").toggle(
        function() {
            $(this).next("tr").hide();
        },
        function() {
            $(this).next("tr").show();
        }
    )
});

回答1:


There is some weirdness among different browsers with toggling TRs. If you place a border="1" in the table in FF you'll see how the toggling works (or doesn't) as you have it currently coded.

If you go with a toggle(fn, fn) it seems to work in FF and IE7. IE8 could be a different story - so check it as well. jQuery .toggle() not working with TRs in IE shows a fix if that's the case.

The following assumes that tfoot tr { display: none; } is present in your CSS.

$(function() {

    var $tr = $("tfoot tr");

    $(".sectionhead").toggle(
        function() {
            $tr.show();
        },
        function() {
            $tr.hide();
        }
    );

});



回答2:


I don't think you want to use toggle() as toggle will use the show() method and set the element display to 'block'. In this case, I think you want to have something a little more custom which will set the tr display to 'table-row'.



来源:https://stackoverflow.com/questions/1256146/using-jquery-toggle-function-on-a-table-row-makes-table-itself-grow

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