jQuery文檔加載完畢的幾種寫法

js中文檔加載完畢。通常在body加一個onload事件或者window.onload = function () {}javascript

jQuery中有好多寫法,平時也不注意,別人一問,還真以爲頭大。html

下面是我整理測試的結果。java

複製代碼
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <script src="jquery-1.7.1.js" type="text/javascript"></script>

</head>

<body style=" overflow-y:scroll;overflow-x:auto;">
<input type="text"  id="dd1" value="" />

<textarea id="tt" cols="30" rows="30"></textarea>
</body>
</html>
        
<script>
var i=1;

//jQuery方式
$(document).ready(function(){
        var str=$("#tt").val()+'\r\n'+'$_A加載完畢'+i;
        $("#tt").val(str);
        i++;
    });

$(function(){
        var str=$("#tt").val()+'\r\n'+'$_B加載完畢'+i;
        $("#tt").val(str);
        i++;
    }) ;

$(function($) {
        var str=$("#tt").val()+'\r\n'+'$_C加載完畢'+i;
        $("#tt").val(str);
        i++;
});

$(window).load(function() {
        var str=$("#tt").val()+'\r\n'+'$_D加載完畢'+i;
        $("#tt").val(str);
        i++;
});

(function() {
        var str=$("#tt").val()+'\r\n'+'$_E加載完畢'+i;
        $("#tt").val(str);
        i++;
})(jQuery)

////////////////////jQuery與別名$可互通/////////////////////////////////
jQuery(document).ready(function(){
        var str=$("#tt").val()+'\r\n'+'jQuery_F加載完畢'+i;
        $("#tt").val(str);
        i++;
    });

jQuery(function() {
        var str=$("#tt").val()+'\r\n'+'jQuery_G加載完畢'+i;
        $("#tt").val(str);
        i++;
})
jQuery(function($) {
        var str=$("#tt").val()+'\r\n'+'jQuery_H加載完畢'+i;
        $("#tt").val(str);
        i++;
});

jQuery(window).load(function() {
        var str=$("#tt").val()+'\r\n'+'jQuery_I加載完畢'+i;
        $("#tt").val(str);
        i++;
});

//js方式
window.onload = function () {
        var str=document.getElementById("tt").value+'\r\n'+'js加載完畢'+i;;
        document.getElementById("tt").value=str;
        i++;
    };
複製代碼
/*注意順序,沒有按照咱們上面的順序出來的,那就是自己加載有前後。
D和I加載的是window,因此慢。

$_E加載完畢1
$_A加載完畢2
$_B加載完畢3
$_C加載完畢4
jQuery_F加載完畢5
jQuery_G加載完畢6
jQuery_H加載完畢7
js加載完畢8
$_D加載完畢9
jQuery_I加載完畢10

*/

參考出處:http://www.cnblogs.com/alex-toni/p/5805918.htmljquery

=====================================================函數

方式1:

$(function(){
initPublish();
});

說明: initPublish() 即爲你要運行的JS函數;這段代碼,放在頁面最低端。

方式2: 

$(document).ready(function () {
// add your code here
initPublish();
$(.a).click( function (){
// add your code here
});
});

方式3:

window.onload = function (){
// add your code here
}

 

參考出處:http://www.jb51.net/article/48140.htmpost

相關文章
相關標籤/搜索