我通过Ajax调用创建了一个div class = box并附加到一个主div.此div class = box根据其内容更改其高度.我需要它的高度,但.height()返回0 ....
$.ajax({ url: "json/news.json",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
var html ="<div class='box'>"+data.box+"</div>";
}
});
// now i want its height
var j = $('.box').height();
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?谢谢
这里有两个问题:
$.ajax是异步的,所以在success回调运行之前它不会创建任何东西.如果你想测量你的盒子,你需要在回调中做到:
$.ajax({ url: "json/news.json",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
var html ="<div class='box'>"+data.box+"</div>";
var j = $('.box').height();
}
});
Run Code Online (Sandbox Code Playgroud)你没有将你的html添加到任何东西,因为它不是DOM的一部分,所以它没有高度.您需要执行以下操作:
success: function(data){
var html ="<div class='box'>"+data.box+"</div>";
$("body").html(html);
var j = $('.box').height();
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
12687 次 |
| 最近记录: |