2013-06-22 84 views
0

我想寫一個插件,它將從服務器加載之前將一些加載動畫綁定到圖片。它工作正常,除了一些情況。我的意思是改變DOM結構。我的插件的邏輯是:JQuery中的實況事件實際上是如何工作的?

(function(window){ 

'use strict'; 

var $ = window.jQuery; 
var console = window.console; 
var hasConsole = typeof console !== 'undefined'; 

var methods = { 
    // plugin initialization 
    init : function(options) { 
     return this.each(function(){ 
      methods._applyImagepreloader.apply(this, options); 
     }); 
    }, 
    // working with each object 
    _applyImagepreloader: function() { 
     // if has class imagepreloader, do nothing 
     if ($(this).hasClass('imagepreloader')) 
      return; 
     // if the image has determined size 
     var width = $(this).width(); 
     var height = $(this).height(); 
     $(this) 
      .clone() 
      .attr('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7') 
      .attr('width', width) 
      .attr('height', height) 
      .addClass('imagepreloader') 
      .insertAfter(this); 
     $(this).hide(); 
     $(this).load(function(){ 
      $(this).next('.imagepreloader').remove(); 
      $(this).fadeIn(); 
     }); 
    } 
}; 

$.fn.imagepreloader = function(options) { 
    return methods.init.apply(this, options); 
}; 

})(window); 

現在,當頁面正在被AJAX和新的圖片廣告出現更新,我的插件不工作。我進行了調查並瞭解到,DOM突變事件可以幫助我,但據我瞭解,它們不受所有瀏覽器的支持。此外,我可以使用setinterval捕捉DOM結構的變化,但我想這不是最佳實踐。所以,也許這個問題已經在JQuery on/live事件中解決了。我想知道他們是如何工作的。他們如何捕捉新DOM元素的外觀?

+0

問題不在於做的IMG插件代碼*本身*而是如何/何時被激發(或不調用)有問題的節點。您需要確保在頁面加載時調用現有img節點上的插件,然後每當插入新的img節點時。 –

+0

@甜菜根 - 甜菜根,但我怎麼能確定新的img節點被插入? –

+0

您是否負責執行插入的代碼?如果是這樣,那麼調用該代碼中的插件。 –

回答

1

當使用事件代理與on,事件總是連接到其不會被動態

$("#Container").on('click','#dynamicallyAddedChildOfContainer',function(){...}); 

加載例如#Container在上面的例子中的靜態元件是其存在於DOM和容器您正在動態添加#dynamicallyAddedChildOfContainer,現在,當您單擊動態添加的元素時,事件氣泡直至容器,並且這是事件觸發的位置。

更多關於事件委託 -

+0

謝謝,pXL。有用的職位。 –

相關問題