我在做什么
我正在创建一个可分发的jQuery小部件库,它在HTML页面上插入一个锚。
问题
在'MyWidget.prototype.Render'方法(JS)中,它给出了以下错误 - “jQuery未定义”但是,它的工作正常MyWidget.prototype.ResolveJqueryAndLoadAdditionalJsAndCss'方法。
HTML代码段
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<a href="http://yahoo.com">Anchor - by user code</a>
<!-- Widget Script: Starts -->
<script type="text/javascript" src="widget.js" ></script>
<Script type="text/javascript">
var customWidget = new MyWidget();
customWidget.Render({ anchorText:'Hola!!!' });
</script>
<!-- Widget Script: Ends -->
</body>
</html>
JS代码(widget.js)
var MyWidget = function() {
// Localize jQuery variable
var jQuery;
// Load jQuery if not present
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
this.ResolveJqueryAndLoadAdditionalJsAndCss();
}
};
} else {
script_tag.onload = this.ResolveJqueryAndLoadAdditionalJsAndCss;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
this.ResolveJqueryAndLoadAdditionalJsAndCss();
}
};
MyWidget.prototype.ResolveJqueryAndLoadAdditionalJsAndCss = function() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
jQuery(document).ready(function($) {
$.when(
$.getScript( "http://www.jacklmoore.com/colorbox/jquery.colorbox.js" ),
$.Deferred(function( deferred ){
$( deferred.resolve );
})
).done(function(){ });
// Loading Custom CSS
var css_link = $("<link>", { rel: "stylesheet", type: "text/css", href: "https://raw.github.com/premasagar/cleanslate/master/cleanslate.css" });
css_link.appendTo('head');
css_link = $("<link>", { rel: "stylesheet", type: "text/css", href: "http://www.jacklmoore.com/colorbox/example4/colorbox.css" });
css_link.appendTo('head');
css_link = $("<link>", { rel: "stylesheet", type: "text/css", href: "widget.css" });
css_link.appendTo('head');
});
};
MyWidget.prototype.Render = function(data){
jQuery(document).ready(function($) {
$('<a href="http://wikipedia.com" class="cleanslate custom widgetExternalPage">' + data.anchorText + '</a>').appendTo('body');
$(".widgetExternalPage").colorbox({iframe:true, width:"80%", height:"80%"});
});
};
答案 0 :(得分:-1)
好吧,你正在重新定义jQuery
。实际上,你重新声明任何变量也在重新设置它的值。在这里,您要将jQuery
的值设置为undefined
。你不应该这样做。
如果您愿意,可以这样做:
var jQuery = jQuery || undefined;
这可能有所帮助,祝你好运!