首页 > 技术文章 > js页面加载函数

whytohow 2016-07-16 13:16 原文

在未加载完文档,使用jquery选择器选择元素后,如果立即绑定事件进行调用,会引起js的报错(can not read property of undefined),导致事件不能绑定成功.

alert($("p")[1].firstChild.nodeValue);

 这时就需要js的页面加载函数

一般有三种

window.onload = function(){
	$("p").bind("click", function() {
		$(this).hide();
	})
}

$(document).ready(function(){
	$("p").click(function(){
		$(this).hide();
	})
})
$(function(){
	$("p").click(function(){
		$(this).hide();
	})
})

//$(function(){})是 $(document.ready(function(){})) 的简写

 

另外jQuery绑定事件的方式有两种

一种 是直接 click(callback(){});

一种是使用 bind函数 bind("click",callback(){});

推荐阅读