2013-05-28 43 views
6
<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.将子页面的内容加载到不可见的临时div。
2.计算该临时分区的高度。
3.将主div和右列的高度更改为该temp div的高度。
4.将子页面的内容加载到主div。
如何在调用另一个函数之前等待div加载?

但是,我知道,我现在这样做的方式是因为使用setTimeout()作为等待要加载的内容即兴的漂亮跛脚 - 我用$(document).ready尝试,但没有运气。使用全局变量(var href)也似乎并不普遍,但通过this运算符$("a.load").click函数apply()也没有工作。

如何做到“正确”?

+0

可能重复[如何要等到一个成分存在?(http://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists) – user2284570

回答

3

使用负载回调

$("#tempMain").load($(this).attr("href"),function(){ 
    resizeDivs(); 
    // do other stuff load is completed 
}); 
+5

没有JQuery? – user2284570

+0

这不适用于本地文件(file://) - 出于安全原因,现代JS会阻止本地文件href。 – Daggar

+0

这里是没有jQuery的代码 –

13

使用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"); 
}); 
+0

这适用于本地文件(file://),其中jQuery的.load()回调没有。 – Daggar

相关问题