我相信这已经被反复讨论过,但我很难过。我正在使用 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/