如何在div准备好后调用函数? [英] How to call a function after a div is ready?

查看:107
本文介绍了如何在div准备好后调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的JavaScript文件中有以下内容:

  var divId =divIDer; 

jQuery(divId).ready(function(){
createGrid(); //向html
添加一个网格});

html看起来像这样:

 < div id =divIDer>< div> 

但是有时候我的createGrid()函数会在我的divIder实际加载到页面之前被调用。那么当我尝试呈现我的网格时,它无法找到指向的合适div并且不会呈现。如何在我的div完全准备好使用后调用函数?



编辑:



m使用Extjs加载div:

  var tpl = new Ext.XTemplate(
'< div id = {} DIVID >< / DIV>');

tpl.apply({

});


解决方案

您可以使用递归来执行此操作。例如:

  jQuery(document).ready(checkContainer); 
$ b $函数checkContainer(){
if($('#divIDer')。is(':visible'))){//如果容器在页面上可见
createGrid(); //添加一个网格到html
} else {
setTimeout(checkContainer,50); //等待50毫秒,然后再试一次


code


$ b基本上,该功能将检查以确保该元素存在且可见。如果是,它会运行你的 createGrid()函数。注意::理想情况下,您只需使用AJAX调用的回调函数来知道容器何时被添加,如果没有,则会等待50毫秒,然后再次尝试。

但这是一种蛮横的,独立的方式。 :)

I have the following in my javascript file:

var divId = "divIDer";

jQuery(divId).ready(function() {
  createGrid();  //Adds a grid to the html
});

The html looks something like:

<div id="divIDer"><div>

But sometimes my createGrid() function gets called before my divIder is actually loaded onto the page. So then when I try to render my grid it can't find the proper div to point to and doesn't ever render. How can I call a function after my div is completely ready to be used?

Edit:

I'm loading in the div using Extjs:

var tpl = new Ext.XTemplate(
'<div id="{divId}"></div>');

tpl.apply({

});

解决方案

You can use recursion here to do this. For example:

jQuery(document).ready(checkContainer);

function checkContainer () {
  if($('#divIDer').is(':visible'))){ //if the container is visible on the page
    createGrid();  //Adds a grid to the html
  } else {
    setTimeout(checkContainer, 50); //wait 50 ms, then try again
  }
}

Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid() function. If not, it will wait 50ms and try again.

Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)

这篇关于如何在div准备好后调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆