<script>
var href;
$(function(){
$("a.load").click(function (e) {
e.preventDefault();
href = this;
// cover all bookmarks
$("."+($(this).attr("class"))).css('border-bottom', 'solid 1px black');
$("."+($(this).attr("class"))).css('background-color', '#F5F5F5');
// uncover chosen bookmark
$("#"+($(this).attr("id"))).css('border-bottom', 'solid 2px white');
$("#"+($(this).attr("id"))).css('background-color', 'white');
$("#tempMain").load($(this).attr("href")); // load content to temp div
setTimeout(function() {resizeDivs();}, 500); // synchronize size of #main and #rightColumn
});
});
function resizeDivs() {
var heightNew = $("#tempMain").css("height");
$("#rightColumn").css('height',heightNew);
$("#main").css('height',heightNew);
// $('#main').load($(href).attr('href'));
$("#main").html($("#tempMain").html()); // is faster than loading again
}
</script>
我正在通过 jQuery 函数将子页面加载到我的主页的选定 div。为了同步主 div 和右列的高度,我使用 jQuery 的 .css()
方法。我希望调整大小看起来平滑,所以我将其解决为以下步骤:
1. 将子页面的内容加载到不可见的temp div。
2. 计算临时分区的高度。
3. 将主分区和右栏的高度更改为该临时分区的高度。
4.加载子页面内容到主div。
但是,我知道我目前的做法很蹩脚,因为使用了 setTimeout()
作为等待内容加载的即兴创作——我试过使用 $(document).ready
但没有运气。使用全局变量 ( var href
) 似乎也不靠谱,但传递 this
$("a.load").click
的运营商通过 apply()
发挥作用也没有用。
如何以“正确”的方式做到这一点?
最佳答案
使用 jquery
function waitForElement(elementPath, callBack){
window.setTimeout(function(){
if($(elementPath).length){
callBack(elementPath, $(elementPath));
}else{
waitForElement(elementPath, callBack);
}
},500)
}
例如使用:
waitForElement("#myDiv",function(){
console.log("done");
});
这里没有jquery
function waitForElement(elementId, callBack){
window.setTimeout(function(){
var element = document.getElementById(elementId);
if(element){
callBack(elementId, element);
}else{
waitForElement(elementId, callBack);
}
},500)
}
例如使用:
waitForElement("yourId",function(){
console.log("done");
});
关于javascript - 如何在调用另一个函数之前等待 div 加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16791479/