:last-child removes the body div



我在jquery中遇到了一个奇怪的问题。我必须删除主体的最后一个子项才能使调整大小功能正常工作。最后一个孩子是twitter社交插件插入的div,已经过时了。

在我的调整大小功能中,我尝试了

$('body:last-child').remove();

文件结构如下

    <body>
        <div>here comes content and stuff</div>
        </div>that´s the div to be removed</div>
    </body>

当调用resize函数时,整个body标记被删除,我得到一个空白页。调整大小功能:

$(document).ready(function() {
                $(window).bind('resize', function() {
                    $('body:last-child').remove();
                    contentStretch();
                    function contentStretch() {
                        $('#content-stretch').css({
                            height: "0"
                        });
                        var page_height =  $('#container').height();
                        var window_height = $(window).height();
                        var difference = window_height - page_height;
                        if (difference < 0) {
                            difference = 0;
                        };
                        $('#content-stretch').css({
                            height: difference + "px"
                        });
                    };
                });
            }); 

:last-child选择器获取其父级的最后一个子级元素,而不查找元素中的最后一个子级。body元素是其父元素的最后一个子元素,因为只有一个body元素。

要删除最后一个div,它是body元素的直接子元素:

$('body > div:last-child').remove();

:last-child选择器是它所附加的项的修饰符。因此,您实际上是在说移除最后一个body元素。

要使代码能够删除body的最后一个直接子项,最简单的更改就是在选择器中添加一个空格。

$('body :last-child').remove();

然而,这有点危险,我建议更具体地说明你要删除的内容。例如,您可以为所有div元素提供一个公共类,例如container。然后,您还可以使用:last-of-type选择器。这样可以确保删除您所期望的内容,即使在DOM结构的同一级别上有不同类型的其他元素。

$('.container:last-of-type').remove();

像这样尝试

$('div:last').remove();

最新更新