jQuery 事件侦听器,用于包含动态内容的完全加载的 DOM

jQuery event listener for fully loaded DOM with dynamic content

本文关键字:DOM 加载 动态 侦听器 事件 用于 包含 jQuery      更新时间:2023-09-26

我正在尝试使用jQuery脚本来对齐两个div的高度。 一切都很好,直到我在其中一个div中有一些动态内容。当我在其中一个div 中硬编码一些静态内容时,例如:

<br>asd<br>asd<br> x 20

两个div 具有相同的 height 属性,但是当我将一些数据从 DB 加载到其中一个div 时,它们是不同的。

我想问题出在 .ready() 侦听器中。文档说它在 DOM 完全加载时触发,但看起来这不是事实。

我的问题是:我应该使用什么样的监听器或其他"技巧"?我认为jquery/javascript解决方案比弄乱css更干净,我希望有这种解决方案。

提前谢谢。

jquery脚本:

$(document).ready(function(){
    var difference = $("#layout-navigation-wrapper").height() - $("#layout-content-wrapper").height();
    if(difference<0)
    {
        var height = $("#layout-content-wrapper").height() -1;
        $("#layout-navigation-wrapper").height(height);
    }
    else if(difference >= 0)
    {
        var height = $("#layout-navigation-wrapper").height() -2;
        $("#layout-content-wrapper").height(height);
    }   
});

jquery 在基本工作中使用事件 document.ready 意味着当所有 DOM 都准备就绪时,直到这里制作 jquery 代码。 适用于没有渲染 jquery 库的选项来渲染 jquery 代码

如果您想在所有 DOM 加载时添加事件,包括内容和图像,则需要执行此操作

$(document).ready(function(){
$(window).load(function(){
    var difference = $("#layout-navigation-wrapper").height() - $("#layout-content-wrapper").height();
    if(difference<0)
    {
        var height = $("#layout-content-wrapper").height() -1;
        $("#layout-navigation-wrapper").height(height);
    }
    else if(difference >= 0)
    {
        var height = $("#layout-navigation-wrapper").height() -2;
        $("#layout-content-wrapper").height(height);
    }   
});
});

一旦网页完全加载了所有内容,包括图像,脚本文件,CSS文件等,您就可以使用window.onload执行脚本。

window.onload = function() {
    var difference = $("#layout-navigation-wrapper").height() - $("#layout-content-wrapper").height();
    if(difference<0)
    {
        var height = $("#layout-content-wrapper").height() -1;
        $("#layout-navigation-wrapper").height(height);
    }
    else if(difference >= 0)
    {
        var height = $("#layout-navigation-wrapper").height() -2;
        $("#layout-content-wrapper").height(height);
    }
};