2014-11-06 55 views
0

我試圖在圖像的src更改時將load事件添加到img標記。由於插件,image被刪除並重新連接,所以我無法真正改變這一點。這是我簡單的HTML當使用jQuery刪除圖像並重新附加圖像時,不會觸發加載事件

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

這是我的骨幹腳本

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 
    } 
}); 

我試圖使用委派事件,但它並沒有真正發揮作用。

+0

您的腳本不完整。事件散列在哪裏? – 2014-11-06 01:34:24

+0

因爲這個http://stackoverflow.com/questions/19335702/how-to-delegate-a-load-dom-event,這些事件被遺漏了,這就是爲什麼我手動附加事件。 – toy 2014-11-06 01:35:37

+0

不能使用沒有事件散列的委託事件。您需要每次重新提交您的視圖以便將事件偵聽器附加到新的'' – 2014-11-06 18:07:11

回答

0

我覺得this.$el返回實際的圖像元素

對於委託的事件,你應該使用一個父元素

,而不是這個

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

嘗試使用此

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

這裏$(document)元素可以是任何東西g是image元素的父親