javascript - 为什么我无法检索为响应 jQuery AJAX 请求而插入的内容的计算高度?

标签 javascript jquery ajax dom

我相信这已经被反复讨论过,但我很难过。我正在使用 jQuery 对返回一些 HTML 的 ASP.NET Web 服务进行 AJAX 调用。那部分工作正常。

我想对返回的 HTML 的高度进行一些计算,但是当调用第一次发生时,我得到的高度为 0。我知道我的计算只是在 AJAX 调用完成之前发生,因为在第二次尝试时它起作用了。如果我清除缓存然后它再次返回 0。

我需要在呈现 html 后触发一个事件。我已经尝试过全局和本地事件,例如 ajaxComplete

$.ajax({
    type: "POST",
    url: "Webservices/Service.asmx/HelloWorld",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        $("#OverlayContent").html(msg.d);
    }
    complete: function(msg) {
        alert($("#OverlayContent").height());
    } 
});

感谢任何帮助。

最佳答案

听起来您的高度计算是在 html 被插入并呈现在 DOM 中之前运行的。确保通过 setTimeout 调用或间隔来错开它。例如:

$.ajax({
    type: "POST",
    url: "Webservices/Service.asmx/HelloWorld",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        $("#OverlayContent").html(msg.d);
        setTimeout(function(){ getHeight();},100);
    }
});

function getHeight(){
    // If our height is 0, set a new timeout and we'll check again
    if($("#OverlayContent").height() === 0){
        setTimeout(function(){ getHeight() }, 100);
    }
    else{
        alert("The height is: " + $("#OverlayContent").height());
    }
}

您需要轮询插入 DOM 并呈现的 html。

关于javascript - 为什么我无法检索为响应 jQuery AJAX 请求而插入的内容的计算高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/967214/

相关文章:

javascript - RSA - PyCrypto 和 Javascript RSA 库 (PidCrypt) 编码问题

javascript - threeJS 将对象从 A 点移动到 B 点

jquery 增量旋转按钮

javascript - Chrome、Firefox 上的全屏模式问题

javascript - pageY on div with overflow-y

javascript - wordpress:有没有办法 Hook 操作/过滤器调用

javascript - jquery 3.1.1 错误 : Object doesn't support property or method 'andSelf'

javascript - 快速加载ajax内容的方法

mysql - 无法从 AJAX POST 成功函数 Express/mySQL 获取数据

jquery - $.get() 在 .each() 循环中,获取 $.get 中的 $(this)