请帮助理解为什么它不工作并帮助使其工作?jQuery不计算总高度div的动态添加子元素
我想计算所有动态添加/放置到DIV元素的子元素的总高度,代码不工作[即子元素的数量每次都会有所不同]。当我检查console.log()中的返回值时,代码返回初始定义值零。
下面是代码和打印scrreen:
//This is the code that dynamically extracts data every second from the server and populates it into to DIV element.
setInterval(function() {
google.script.run.withSuccessHandler(function(data) {
var temp3 = '';
for (var i = 0; i < data.length; i++) {
temp3 += '<p>' + data[i].join() + '</p>';
}
document.getElementById("item1").innerHTML = temp3;
}).getReadyLine();
}, 1000);
//This is the code that should calculate the total height of all the children elements of DIV element. But it is not working, not calculating, it displays 0 on the console.log().
var outerHeight1 = 0;
$("#item1").children().each(function() {
outerHeight1 += $(this).outerHeight();
});
</script>
//This is the code for DIV.
<div class="item1" id="item1">
PS
Update: included the code inside setInerval like this:
<script>
$(document).ready(function() {
setInterval(function() {
google.script.run.withSuccessHandler(function(data) {
var temp3 = '';
for (var i = 0; i < data.length; i++) {
temp3 += '<p>' + data[i] + '</p>';
}
document.getElementById("item1").innerHTML = temp3;
}).getReadyLine();
var outerHeight1 = 0;
$("#item1").children().each(function() {
outerHeight1 += $(this).outerHeight(true);
return outerHeight1;
});
console.log(outerHeight1);
}, 1000);
/*
var outerHeight1 = 0;
$("#item1").children().each(function() {
outerHeight1 += $(this).outerHeight();
}); */
var outerHeight2 = 0;
$("#item2").children().each(function() {
outerHeight2 += $(this).outerHeight(true);
})
$("#item1").animate({
scrollTop: outerHeight1
}, 10000);
setTimeout(function() {
$("#item1").animate({
scrollTop: 0
}, 10000);
}, 3000);
setInterval(function() {
// 4000 - it will take 4 secound in total from the top of the page to the bottom
$("#item1").animate({
scrollTop: outerHeight1
}, 10000);
setTimeout(function() {
$("#item1").animate({
scrollTop: 0
}, 10000);
}, 4000);
}, 4000);
$("#item2").animate({
scrollTop: outerHeight2
}, 8000);
setTimeout(function() {
$("#item2").animate({
scrollTop: 0
}, 8000);
}, 8000);
setInterval(function() {
// 4000 - it will take 4 secound in total from the top of the page to the bottom
$("#item2").animate({
scrollTop: outerHeight2
}, 8000);
setTimeout(function() {
$("#item2").animate({
scrollTop: 0
}, 8000);
}, 8000);
}, 8000);
console.log($("#item1").outerHeight());
console.log(outerHeight1);
});
</script>
如果你可以在这里发布一个小提琴或代码段,这将是有益的。 – gaganshera
问题是,你只计算一次高度,这是在任何元素添加到'#item1'之前完成的。 – Titus
确切地说...你在setInterval之外做的事情 – charlietfl