jquery事件调用出错

一    问题:想实现异步加载器的现实和隐藏。刚开开始把JS代码写成如下所示,一直都没显示。

//异步加载器现实
function showLoader() {
$.mobile.loading("show", {
text: "加载中..",
textVisible: true,
theme: 'a',
textonly: false,
html: '',
});
}
//异步加载当月数据
new function () {
var myDate = new Date();
myDate.getFullYear();
myDate.getMonth();
$.ajax({
type: 'post',
url: '/MonthOutput/GetMonthOutput',
dataType: "json",
beforeSend: showLoader,

data: { date: myDate.getFullYear().toString() + '/' + myDate.getMonth().toString() },//获取当前对象的属性(自定义属性)sno的值,用自定义属性保存相应需要的数据
success: function (json) {
$.mobile.loading('hide');
if (json != null) {
RenderChartmyself(json);
} else {
alert("抱歉,报表数据加载失败!");
}
}
})

}

 

二  解决办法: 将ajax异步加载放入$(document).ready(function () {}中则OK  如下所示。

//异步加载器现实
function showLoader() {
$.mobile.loading("show", {
text: "加载中..",
textVisible: true,
theme: 'a',
textonly: false,
html: '',
});
}
//异步加载当月数据
$(document).ready(function () {
new function () {
var myDate = new Date();
myDate.getFullYear();
myDate.getMonth();
$.ajax({
type: 'post',
url: '/MonthOutput/GetMonthOutput',
dataType: "json",
beforeSend: showLoader,

data: { date: myDate.getFullYear().toString() + '/' + myDate.getMonth().toString() },//获取当前对象的属性(自定义属性)sno的值,用自定义属性保存相应需要的数据
success: function (json) {
$.mobile.loading('hide');
if (json != null) {
RenderChartmyself(json);
} else {
alert("抱歉,报表数据加载失败!");
}
}
})

}
});

 

三  原因分析

 

如果你想要一个事件运行在你的页面上,你必须在$(document).ready()里调用这个事件。所有包括在$(document).ready()里面的元素或事件都将会在DOM完成加载之后立即加载,并且在页面内容加载之前。 
If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as theDOM is loaded and before the page contents are loaded. 

$(document).ready(function() { 
// put all your jQuery goodness in here. 
}); 

 使用 $(document).ready(),你能让你的事件在window加载之前加载或触发。所有你写在这个方法里面的都准备在最早的时刻加载或触发。也就是说,一旦DOM在浏览器中注册后,$(document).ready()里的代码就开始执行。这样用户在第一眼看见页面元素时,特效就可以运行了。

 

posted on 2016-03-11 15:30  木色小罗  阅读(241)  评论(0编辑  收藏  举报

导航

诗与远方