简体   繁体   English

使用jQuery删除图像并重新附加图像时,不会触发载入事件

[英]On load event is not fired when image is removed and reattached using jQuery

I'm trying to add load event to img tag when the src of the image is changed. 我试图在图像的src更改时将load事件添加到img标签。 The image is deleted and reattached due to a plugin, so I can't really changed that. image由于插件而被删除并重新附加,因此我无法真正更改它。 This is my simplified HTML 这是我的简化HTML

<div class="twitter">
    <img src="picture.jpg" />
</div>

And this is my Backbone script 这是我的Backbone脚本

var TwiterView = Backbone.View.extend( {
    render : function() {
        var self = this;

        this.$el.on('load', 'img', function() {
            self.updateTwitterPreview();
        }).each(function() {
            if(this.complete) $(this).trigger('load');
        });

        this.$el.find('img').on("remove", function () {
            alert("Element was removed"); // This one got fired when the event is removed
        });
        return this;
    },
    updateTwitterPreview: function() {
        alert('test'); // This one got fired when the page is loaded the first time, but not when the image is changed
    }
});

I'm trying to use delegated event but it didn't really work. 我正在尝试使用委托事件,但它实际上没有用。

I think this.$el returns the actual image element 我认为this.$el返回实际的图像元素

For delegated event you should use a parent element 对于委托事件,应使用父元素

instead of this 代替这个

this.$el.on('load', 'img', function() {

try using this 尝试使用这个

$(document).on('load', 'img', function() {

here $(document) element can be anything which is parent to the image elements 这里$(document)元素可以是image元素的父元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM