页面加载后运行javascript

时间:2011-04-01 05:33:07

标签: javascript jquery pageload

setup_account ui-mobile-viewport ui-overlay-c

当我按照这样的方式加载页面时:

var location    =   location.href+"&rndm="+2*Math.random()+" #updatecomment0>*"
$("#updatecomment0").load(location, function(){});

我在updatecomment0 div上运行了多个脚本:

<div id="updatecomment0">
    <div id="javascript1">hi</div>
    <div style="float:right;" class="javascript2">delete</div>
</div>

我不知道在页面加载后如何使其他JavaScripts运行 有人可以告诉我如何处理这件事 谢谢

10 个答案:

答案 0 :(得分:12)

Use $(document).ready()

答案 1 :(得分:5)

使用jQuery,你可以很容易地做到这一点。

jQuery(document).ready(function(){
    alert('Your DOM is ready.Now below this u can run all ur javascript');
});

答案 2 :(得分:2)

ready

中编写代码
jQuery(document).ready(function(){

// write here
});

建议:使用livebind

答案 3 :(得分:2)

以下是您的示例布局

<script type="text/javascript">
    $(document).ready(function(){
        /// here you can put all the code that you want to run after page load
        function Javascript1(){
            //code here
        }

        function Javascript2(){
            // code here
        }

        $("#btnOK").live('click',function(){
            // some codes here
            Javascript1();
            Javascript2();
        });

    });
</script>

<div id="MyDiv">
    <input type="button" id="btnOK" value="OK"/>
</div>

答案 4 :(得分:1)

除非您在加载页面之前需要javascript来执行某些操作,否则请将脚本添加到html文档的底部,就在 body 结束标记之前。 页面将加载更快,您可以在js文件中执行任何需要的操作,而无需文档就绪函数。

如果脚本是最后加载的,那么DOM已经保证“准备就绪”。

答案 5 :(得分:1)

$(window).load(function() {
    // code here
});

答案 6 :(得分:1)

$(document).ready()就是您所需要的一切。

答案 7 :(得分:0)

您可以使用setTimeout方法让JavaScript等待指定的时间:

.setTimeout("name_of_function()",time_in_millis);

答案 8 :(得分:0)

我希望这也可以帮助你,我有一个类似的问题,我通过在页面中加载内容之后调用以下内容来修复它(就像在一个页面显示在div中的AJAX请求之后): / p>

(function($) {
 $(document).ready(function() {
  // your pretty function call, or generic code
 });
}(jQuery));

请记住不要在加载的文档中调用它,而是在加载它的函数中调用它。

答案 9 :(得分:0)

使用vanilla Javascript,可以这样做:

<html>
<head>
<script type="text/javascript">

// other javascript here

function onAfterLoad() { /*...*/ }

// other javascript here

</script>
</head>
<body>

<!-- HTML content here -->

<!-- onAfterLoad event handling -->
<div style="display:none;"><iframe onload="onAfterLoad();"></iframe></div>
</body>
</html>