点击事件报错TypeError: this.$setScheduleBtn.on is not a function求助
解决jQuery 1.3.2中
TypeError: this.$setScheduleBtn.on is not a function的问题 这个问题的核心原因很明确——你用的jQuery 1.3.2版本太低了,.on()方法是在jQuery 1.7才正式引入的,1.3.2根本不支持这个API,这就是为什么本地运行报错,而JSFiddle里能正常工作(因为JSFiddle默认的jQuery版本通常比1.3.2新很多)。
给你两个可行的解决方案:
方案1:改用旧版事件绑定方法 .click() 或 .bind()
对于点击事件,直接用.click()是最简洁的方式,在jQuery 1.3.2中完全支持:
bindEvents: function() { this.$setScheduleBtn.click(this.showReportScheduler.bind(this)); }
如果以后需要绑定其他类型的事件(比如mouseover),可以用.bind(),兼容性同样没问题:
bindEvents: function() { this.$setScheduleBtn.bind('click', this.showReportScheduler.bind(this)); }
方案2:用jQuery的.proxy()解决this指向问题(更兼容旧浏览器)
注意Function.prototype.bind()是ES5的特性,如果你需要兼容IE8及以下这类非常旧的浏览器,建议用jQuery 1.3.2已经支持的$.proxy()来绑定this:
bindEvents: function() { this.$setScheduleBtn.bind('click', $.proxy(this.showReportScheduler, this)); }
修改后的完整代码
这里给你整合好的完整代码,直接替换原来的脚本部分即可:
<span class="btn" id="setScheduleBtn">Set Schedule</span> <div id="reportSchedule" name="reportSchedule" style="display: none;">text</div> <script type="text/javascript"> /******************/ /** Set Schedule **/ /******************/ (function() { var schedule = { report: [], // 修正了选择器错误:原代码写的#report_schedule,对应HTML的id是reportSchedule template: $('#reportSchedule').html(), // Init functions init: function() { this.cacheDom(); this.bindEvents(); }, // Cache elements from DOM cacheDom: function() { this.$setScheduleBtn = $('#setScheduleBtn'); this.$reportSchedule = $('#reportSchedule'); }, // Set events bindEvents: function() { this.$setScheduleBtn.bind('click', $.proxy(this.showReportScheduler, this)); }, // Display on click showReportScheduler: function() { this.$reportSchedule.toggle(); } }; schedule.init(); })(); </script>
另外还要提醒你:原来代码里的template: $('#report_schedule').html()选择器写错了,HTML里的div id是reportSchedule,不是report_schedule,虽然这个不是当前报错的原因,但后续如果用到这个模板的话会出问题,我已经在上面的代码里修正了。
内容的提问来源于stack exchange,提问作者Imnotapotato
相关产品推荐
相关产品推荐

