jquery加载用户界面与getScript导致错误与undefined datepicker
问题描述:
所以我想创建一个小部件去第三方网站,小部件也使用jquery用户界面,但试图让datepicker工作只是不工作预期。jquery加载用户界面与getScript导致错误与undefined datepicker
这是我的代码。
(function() {
// Localize jQuery variable
var myJquery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '3.2.1') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js");
script_tag.onload = scriptLoadHandler;
script_tag.onreadystatechange = function() { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
console.log('need to load latest jQuery')
} else {
console.log('dont need to load jQuery')
myJquery = window.jQuery;
loadJQueryUi();
}
function scriptLoadHandler() {
console.log('latest jQuery loaded')
myJquery = jQuery.noConflict(true);
loadJQueryUi();
}
function loadJQueryUi() {
console.log('main function')
/******* Load UI *******/
myJquery.getScript('https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js', function() {
myJquery = jQuery.noConflict(true);
console.log('loaded jquery UI')
// jQueryApr(document).ready(function ($) {
setHandlers(myJquery)
// });
});
/******* Load UI CSS *******/
var css_link = myJquery("<link>", {
rel: "stylesheet",
type: "text/css",
href: "https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css"
});
css_link.appendTo('head');
}
function setHandlers($) {
console.log('document ready')
$('#start-date').datepicker({
dateFormat: "M dd, yy",
minDate: 'D',
numberOfMonths: 1,
onSelect: function() {
console.log($(this).val())
}
});
}
})();
运行上面我得到的datepicker函数没有定义。但如果我将日期选择器函数包装在焦点事件中,即。
$(document).on('focus', '#start-date', function(){
$('#start-date').datepicker({
dateFormat: "M dd, yy",
minDate:'D',
numberOfMonths:1,
onSelect:function() {
console.log($(this).val())
}
});
});
这工作..也试过包装我的setHandlers函数与文档准备,但没有任何效果。我的问题有没有明显的问题?
答
JQuery在全局范围内并不存在,而在匿名函数的范围内。如果你想使用Jquery函数,比如datepicker,你需要通过Jquery对象myJquery访问该函数。它在document.focus代码块内部工作,因为Jquery已在代码运行时全局加载。您可能需要在诸如document.focus或document.ready之类的事件处理程序中保留datepicker调用,以便按预期工作。
我通过函数setHandlers(myJquery)传递myJquery ..这不正确吗? – Lee
你说得对,我现在明白了。然而,鉴于你所描述的情况,我在答案中描述的问题似乎仍然是发生了什么。因为它正在被传入,而不是全局存在,所以看起来你不能正常链接函数,这意味着你仍然需要在其他地方执行该代码,例如在焦点事件中。 – Josherwoodev