[英]Running jQuery once body has loaded
身体加载后,我想运行一些JS。 我的框架从两个不同的静态文件而主体是动态文件中加载页眉/页脚。 因此,在线阅读时,我可以将$(elem).load(function())放在正文的末尾,并在页面加载时运行该函数? 我短暂地尝试了一下,但似乎没有用。
{%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">
</div>
<script>
$("#contentMain").load(function(){
alert("It worked!");
//run some stuff here
});
</script>
{%include file='/var/www/include/tpl/footer.tpl'%}
任何有关如何使它工作的帮助将不胜感激!
jQuery有一个方便的小功能,您可以在正文加载后将其附加到文档上以运行功能。 它是就绪功能。
$(document).ready(function() {
//Place code here to do stuff
});
这样,您可以确保在运行函数内部的任何内容之前,已加载主体及其所有内容。
在您的情况下,由于脚本的位置,您无需等待。 在解析其上方的元素之前,不会解析/执行脚本。 因此,可以安全地假定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">
</div>
<script>
alert("It worked!");
//run some stuff here
</script>
{%include file='/var/www/include/tpl/footer.tpl'%}
您可以使用jquery的document.ready执行此操作。
在标题上,包括jquery引用。
<script type="text/javascript">
$(document).ready(function() {
alert("It worked!");
});
</script>
</head>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.