javascript - JQuery 模块模式:单击切换功能无法使用
问题描述
当我尝试访问方法“dropDownUserInfo”时单击它会给出错误[无法读取未定义的属性'slideToggle']
代码:
(function(){
var homePage = {
init: function(){
this.cacheDom();
this.bindEvent();
},
cacheDom: function(){
this.$userInfo = $('.user-info a');
this.$userContent = $('.user-info-content');
},
bindEvent: function(){
this.$userInfo.on('click', this.dropDownUserInfo);
},
dropDownUserInfo: function(){
this.$userContent.slideToggle(500);
this.$userInfo.toggleClass('active');
},
}
homePage.init();
})();
解决方案
this
在事件处理方法dropDownUserInfo
函数中,将引用引发事件的 DOM 元素。
你可以使用Function.bind()
它来设置它的上下文。
this.$userInfo.on('click', this.dropDownUserInfo.bind(this));
这是一个例子
(function() {
var homePage = {
init: function() {
this.cacheDom();
this.bindEvent();
},
cacheDom: function() {
this.$button = $('button');
},
bindEvent: function() {
this.$button.on('click', this.buttonClick.bind(this));
this.$button.on('click', this.buttonClick2);
},
buttonClick: function() {
this.$button.toggleClass('active');
},
buttonClick2: function() {
console.clear();
this.$button.text('active'); //Will throw error
}
}
homePage.init();
})();
.active {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Click Me</button>
推荐阅读
- node.js - 如何在 Windows 上使用 nvm 运行 npm 命令?
- python - 在 Kedro 管道中添加参数
- asp.net-mvc - MVC RedirectResult 到带有模型的新页面
- python - Selenium - 通过下拉菜单迭代 - 让页面加载
- javascript - React Native:firestore/firebase 期望 collection() 的第一个参数是 CollectionReference ......如何?
- javascript - git克隆到我的项目后如何访问一个包?
- flutter - 无法使用 openid_client 通过带有 keycloak 的 pkce Flutter 应用程序进行身份验证
- c++ - 从 FreeRTOS 队列调度 TinyFSM 事件
- node.js - 使用 Node/Expressjs 调用方法
- rxjs - RxJs BehaviourSubject 没有将其当前值提供给 forkJoin.pipe