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

Dus*_*ine 3 javascript ajax jquery dom

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

我想对返回的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());
    } 
});
Run Code Online (Sandbox Code Playgroud)

我感谢任何帮助.

ajm*_*ajm 7

听起来你的高度计算是在插入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());
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要轮询插入到DOM中的html并进行渲染.