2013-06-27 40 views
0

我想运行一次JS加载正文后。我的框架从两个不同的文件加载页眉/页脚,这两个文件是静态的,而主体是动态的。因此,在线阅读我可以将$(elem).load(function())放在body的末尾,当页面加载时它会运行该函数?我试了一下,但似乎没有工作。运行jQuery,一旦body已经加载

{%include file='/var/www/include/tpl/header.tpl'%} 
<div id="contentMain"> 
     <h1>{%$heading%}</h1> 
     {%if isset($Details)%} 
       <h4>Details</h4> 
       {%$Details%} 
     {%/if%} 
     {%$table%} 
</div> 
<div id="space"> 
&nbsp; 
</div> 
<script> 
     $("#contentMain").load(function(){ 
       alert("It worked!"); 
       //run some stuff here 
     }); 
</script> 
{%include file='/var/www/include/tpl/footer.tpl'%} 

任何有关如何得到这个工作的帮助将不胜感激!

+0

了''没有加载事件。尝试使用窗口加载事件。但是,就你的情况而言,直到元素准备就绪后,代码才会被执行,因此你根本不需要等待。 –

+0

document.ready?文档加载后的加载情况? – Sakthivel

回答

0

在你的情况下,你不需要等待,因为你的脚本的位置。该脚本不会被解析/执行,直到它上面的元素被解析。因此,假设contentMain div是安全的,并且它的后代已准备好被操纵。

{%include file='/var/www/include/tpl/header.tpl'%} 
<div id="contentMain"> 
     <h1>{%$heading%}</h1> 
     {%if isset($Details)%} 
       <h4>Details</h4> 
       {%$Details%} 
     {%/if%} 
     {%$table%} 
</div> 
<div id="space"> 
&nbsp; 
</div> 
<script> 
    alert("It worked!"); 
    //run some stuff here 
</script> 
{%include file='/var/www/include/tpl/footer.tpl'%} 
3

jQuery有一个方便上手的小​​功能,您可以附加到文档以在主体加载后运行功能。这是ready函数。

$(document).ready(function() { 
    //Place code here to do stuff 
}); 

这样做,这样,就可以保证身体及其所有内容的以前任何的东西装的函数运行中。

+0

我已经准备好了中的其他零碎碎片。这是作为一个静态模板加载的,我并不是真的想要应用到每一个页面,因为内容是动态的,JS正在改变我不一定在那里。我想要做的是能够加载元素后加载另一个函数。 ready()可以被多次调用吗? –

+0

@ user2518122是的,它可以被称为无限次。如果dom已经准备就绪,则立即调用回调。 –

0

您可以使用jquery的document.ready来做到这一点。

在标题上包含jquery引用。

<script type="text/javascript"> 
    $(document).ready(function() { 
    alert("It worked!"); 
    }); 
</script> 
</head> 
相关问题