[英]Working with an image error event in a Backbone view
Within an Underscore template used by a Backbone view I have an image. 在骨干视图使用的下划线模板中,我有一个图像。 I'm trying to attach to the error event and change the image source if the original image is not found.
我试图附加到错误事件并在未找到原始图像的情况下更改图像源。
Based on this similar question , I took the following approach: 基于这个类似的问题 ,我采用了以下方法:
render: function() {
var self = this;
this.$el.html( this.template( { person: this.model.toJSON() } ) );
this.$el.find('img.employee-image').on('error', function(evt) { this.src = "assets/images/_noimage.gif"; });
return this;
}
This works perfectly well, but if I try to move the changing of the src to a separate method in the view, the method will be called but the image will not change. 这可以很好地工作,但是如果我尝试将src的更改移至视图中的单独方法,则将调用该方法,但图像不会更改。
render: function() {
var self = this;
this.$el.html( this.template( { person: this.model.toJSON() } ) );
this.$el.find('img.employee-image').on('error', function(evt) { self.handleMissingImage(evt); });
return this;
},
handleMissingImage: function(evt) {
// This by itself did not work.
// this.src = "assets/images/_noimage.gif";
var i = $(evt.currentTarget);
i.src = "assets/images/_noimage.gif";
console.log(i.src);
}
Logging the src out shows "assets/images/_noimage.gif" but the image will not appear. 注销src将显示“ assets / images / _noimage.gif”,但图像不会出现。 I know it exists because the first approach outlined above works fine.
我知道它的存在是因为上面概述的第一种方法效果很好。
What am I missing here? 我在这里想念什么?
I think your problem is right here: 我认为您的问题就在这里:
i.src = "assets/images/_noimage.gif";
In your handleMissingImage
function you say: 在
handleMissingImage
函数中,您说:
i = $(evt.currentTarget);
so i
is a jQuery object, not a raw DOM element. 所以
i
是一个jQuery对象,而不是原始的DOM元素。 That means that you want to say i.attr('src', ...)
to change the src
attribute or don't bother wrapping evt.currentTarget
at all. 这意味着您想说
i.attr('src', ...)
来更改src
属性,或者根本不用包装evt.currentTarget
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.