【问题标题】:jQuery event listener for fully loaded DOM with dynamic content带有动态内容的完全加载 DOM 的 jQuery 事件监听器
【发布时间】:2013-01-28 13:30:05
【问题描述】:

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

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

两个 div 具有相同的高度属性,但是当我将一些数据从 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);

    }   
});

【问题讨论】:

  • 如何以及何时将数据库内容加载到 DIV 中?
  • 我这样做完全一样:

    ${ content?.text}

    而且我不知道它是什么时候加载的,但它必须在脚本调用之后。

标签: javascript jquery css dom


【解决方案1】:

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);

    }   
});
});

【讨论】:

    【解决方案2】:

    您可以在网页完全加载所有内容(包括图像、脚本文件、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);
    
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 2022-01-23
      • 2016-05-06
      相关资源
      最近更新 更多