van*_*ert 15 javascript jquery
<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>
Run Code Online (Sandbox Code Playgroud)
我正在通过jQuery函数将子页面加载到我的主页面的选定div中.为了同步主div和右列的高度我正在使用jQuery的.css()方法.我希望调整大小看起来很顺利,所以我已经解决了以下步骤:
1.将子页面的内容加载到不可见的临时div.
2.计算临时div的高度.
3.将主div和右列的高度更改为该临时div的高度.
4.将子页面的内容加载到主div.
但是,我知道我目前这样做的方式非常蹩脚,因为使用setTimeout()等待加载内容的即兴创作 - 我尝试过使用$(document).ready但没有运气.使用全局变量(var href)似乎也不是艺术,但通过函数的this运算符也不起作用.$("a.load").clickapply()
如何做到"正确"的方式?
Zee*_*v G 24
用jquery
function waitForElement(elementPath, callBack){
window.setTimeout(function(){
if($(elementPath).length){
callBack(elementPath, $(elementPath));
}else{
waitForElement(elementPath, callBack);
}
},500)
}
Run Code Online (Sandbox Code Playgroud)
例如使用:
waitForElement("#myDiv",function(){
console.log("done");
});
Run Code Online (Sandbox Code Playgroud)
这里没有jquery
function waitForElement(elementId, callBack){
window.setTimeout(function(){
var element = document.getElementById(elementId);
if(element){
callBack(elementId, element);
}else{
waitForElement(elementId, callBack);
}
},500)
}
Run Code Online (Sandbox Code Playgroud)
例如使用:
waitForElement("yourId",function(){
console.log("done");
});
Run Code Online (Sandbox Code Playgroud)
使用加载回调
$("#tempMain").load($(this).attr("href"),function(){
resizeDivs();
// do other stuff load is completed
});
Run Code Online (Sandbox Code Playgroud)