下午想编写一个jquery插件,结果在(function(){})(jQuery);这个问题上遇到了问题
插件的代码如下
;(function($){
$.myplugin = $.myplugin || {};
$.extend($.myplugin,{
version:"1.0",
dialog:{
mAlert:function(title,text,callback) {
var alertDiv = '<div style="position:absolute;top:100px;left:200px;width: 396px;height: 240px;border: 2px #3385ff solid;">'+
'<div style="width: 396px;height: 40px;background-color: #3385ff;">' +
'<p style="text-align: center;color: white;margin: 0;line-height: 40px;">'+title+'</p>'+
'</div>'+
'<div style="width: 396px;height: 160px;background-color: #ffffff;">'+
'<p style="text-align: center;color: black;margin: 0;line-height: 160px;">'+text+'</p>'+
'</div><div style="width: 396px;height: 40px;">'+
'<button style="margin-left:15px;padding:5px 7px;background-color: #FFFFFF;">确定</button>'+
'</div>'+
'</div>';
var $alertDiv = $(alertDiv);
$("body").append($alertDiv);
}
}
});
})(jQuery);
然后我在页面中调用一下,发现无法调用$.myplugin.dialog.mAlert()这个方法。这是怎么回事呢,
然后我又试着在页面中的$(function() {})调用$.myplugin.dialog.mAlert(),结果成功了,这是为什么呢,百思不得其解,然后求助于万能的百度吧
于是我就找到了这个 http://www.linuxidc.com/Linux/2014-08/105462.htm
好的,原真的原因就是这个:(function(){...})()函数的执行时机并不是在DOM加载完毕后才执行,而是随着页面自上而下来执行。也就是说插件在执行的时候,DOM还没有加载完毕,果然在我将引入插件的那个<script></script>标签放在DOM的最后,再执行的时候,成功弹出提示框。