我确实看过this quesiton尽管我可以弄清楚如何实现这一点。
基本代码覆盖是:
jQuery.noConflict();
jQuery(document).ready(function($){
$("button").click(function(e){
popupOverlay();
popupDisplay();
e.preventDefault();
});
function popupOverlay() {
var overlayCss = {
"width" : $(document).width(),
"height" : $(document).height(),
"display" : 'block'
}
$("#popupOverlay").css(overlayCss);
}
function popupDisplay() {
var popup = $("#popup");
etc etc code to work out the central position for popup
$(popup).css({
'top': yPosition + 'px',
'left': xPosition + 'px',
'display' : 'block'
});
}
});
上面的函数工作正常,尽管我想在窗口大小调整时重新调用上面的函数,方法是将其添加到上面的下面:
jQuery(window).resize(function() {
popupOverlay();
popupDisplay();
});
我收到的错误是:popupOverlay 未定义
我尝试将弹出函数移出准备好的文档,但随后出现错误:$ 不是函数
我必须非常小心地处理这段代码,确保它不会与网站上已使用的其他 JavaScript 库产生任何冲突。
最佳答案
它不起作用,因为函数 popupOverlay
和 popupDisplay
位于 $(document).ready
内部,而您试图在外部访问它声明的范围。
像这样重新排列您的代码。
jQuery.noConflict();
// DOM Ready event
jQuery(document).ready(function ($) {
$("button").click(function (e) {
popupOverlay();
popupDisplay();
e.preventDefault();
});
});
//window resize event
jQuery(window).resize(function () {
popupOverlay();
popupDisplay();
});
//custom functions
function popupOverlay() {
var overlayCss = {
"width": $(document).width(),
"height": $(document).height(),
"display": 'block'
}
jQuery("#popupOverlay").css(overlayCss);
}
function popupDisplay() {
var popup = jQuery("#popup");
//etc etc code to work out the central position
//for popup
jQuery(popup).css({
'top': yPosition + 'px',
'left': xPosition + 'px',
'display': 'block'
});
}
关于javascript - 从文档就绪外部调用时未定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6634928/