You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Backbone.js视图事件失效报错:addBgColor不是函数

问题分析与解决方案

嘿,我一眼就发现问题出在哪儿啦!你遇到的报错是因为错误使用了jQuery的方法名——jQuery里根本没有addBgColor()和removeBgColor()这两个方法,你把添加/移除CSS类的方法名写错了。

具体错误点

在你的视图事件处理函数里:

addBgColor: function(){
 this.$el.addBgColor('bgColorImage');
},
removeBgColor: function(){
 this.$el.removeBgColor('bgColorImage');
}

这里的addBgColor和removeBgColor是不存在的方法,jQuery中用于操作CSS类的正确方法是addClass()和removeClass()。

修正后的代码

把事件处理函数改成下面这样就可以正常工作了:

var app = app || {};
app.singleFlowerView = Backbone.View.extend({
 tagName: 'article',
 className: 'flowerListItem',
 template: _.template( $("#flowerElement").html() ),
 render: function(){
 var flowerTemplate = this.template(this.model.toJSON());
 this.$el.html(flowerTemplate);
 return this;
 },
 events: {
 'mouseover': 'addBgColor',
 'mouseout': 'removeBgColor'
 },
 addBgColor: function(){
 // 改用jQuery的addClass方法
 this.$el.addClass('bgColorImage');
 },
 removeBgColor: function(){
 // 改用jQuery的removeClass方法
 this.$el.removeClass('bgColorImage');
 }
});

补充说明

Backbone视图的$el是一个jQuery对象,所以所有对它的DOM操作都要遵循jQuery的API规范。你配置的CSS类bgColorImage会在鼠标悬停时被添加到元素上,鼠标移出时被移除,这样就能实现你想要的背景色变化效果啦。

内容的提问来源于stack exchange,提问作者user6398538

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:07:49