gpt4 book ai didi

javascript - 如何修复 :"Cannot read property ' init' of undefined TypeError”?

转载 作者:行者123 更新时间:2023-11-30 08:21:23 24 4
gpt4 key购买 nike

我使用 Jquery-3.2.1,Jquery-Ui 1.12.1。在我的 JavaScript 文件中:

window.TruyenOnlineScript = (function () {
var _this = {};

_this.init = function () {
_this.initSearchMobile();
_this.initSidebar();
};

_this.initSearchMobile = function () {
//Open Input Search Mobile
$('.js-open-search-box-mobile').on('click', function (event) {
event.preventDefault();
$('body').addClass('open-search-box');
setTimeout(function () {
$('#js-search-input-mobile').focus()
}, 500);
});
};

_this.initSidebar = function () {
//Open Navbar Moblie
$('.js-open-sidebar').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
$('body').addClass('open-sidebar');
});
};

})();

$('document').ready(function () {
window.TruyenOnlineScript.init();
});

但我收到错误“init of undefined”:

enter image description here

谁能告诉我如何解决它?谢谢!

最佳答案

您正在将 window.TruyenOnlineScript 设置为立即调用的函数表达式的返回值:

window.TruyenOnlineScript = (function () {
. . .
})();

但该表达式不返回任何值,因此 window.TruyenOnlineScript 最终变为 undefined(这就是为什么您不能调用 init() undefined 上)。

您需要让 IIFE 返回一个对象供 TruyenOnlineScript 引用。

window.TruyenOnlineScript = (function () {
var _this = {};

_this.init = function () {
_this.initSearchMobile();
_this.initSidebar();
};

_this.initSearchMobile = function () {
//Open Input Search Mobile
$('.js-open-search-box-mobile').on('click', function (event) {
event.preventDefault();
$('body').addClass('open-search-box');
setTimeout(function () {
$('#js-search-input-mobile').focus()
}, 500);
});
};

_this.initSidebar = function () {
//Open Navbar Moblie
$('.js-open-sidebar').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
$('body').addClass('open-sidebar');
});
};

return _this; // <-- Now this will be returned

})();

$('document').ready(function () {
window.TruyenOnlineScript.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 如何修复 :"Cannot read property ' init' of undefined TypeError”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com