Click事件导致错误`TypeError:this。$ varName.on不是函数`,它不是函数

时间:2018-01-07 12:36:21

标签: javascript jquery modular-design

我有这个确切的代码:

<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: [], 
        template: $('#report_schedule').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.on('click', this.showReportScheduler.bind(this));
        }, 
        // Display on click
        showReportScheduler: function() {
            this.$reportSchedule.toggle();
        }

    };
    schedule.init();

})();
</script>

在我的本地计算机项目上运行此代码 - 我在控制台中收到此错误结果: TypeError: this.$setScheduleBtn.on is not a function 没有切换。 jQuery被加载到标记中。 html代码出现在脚本之前。 jQuery JavaScript Library v1.3.2

这是一个JSfiddle,具有正确运行的确切代码: https://jsfiddle.net/t6hprf4x/

可能是什么问题?

1 个答案:

答案 0 :(得分:1)

根据documentation版本on中添加了1.7功能,这意味着您使用的版本没有此功能。

您必须使用较新版本的库或使用click函数添加点击侦听器。

this.$setScheduleBtn.click(this.showReportScheduler.bind(this));