2011-08-28 19 views
6

Esiste un evento o una funzione semplice per chiamare una richiamata quando esiste un elemento specifico nella pagina. Non sto chiedendo come verificare se esiste un elemento.jQuery elemento esiste evento

come esempio

$("#item").exists(function(){ }); 

ho finito per usare l'evento ready

$("#item").ready(function(){ }); 
+2

Che cosa vuoi fare? –

+0

La funzione ready non sembra funzionare in questo modo @Drake. Vedi questo violino come esempio: http://jsfiddle.net/YDn5f/ –

risposta

1

Date un'occhiata alla funzione .Live. Esegue su tutti gli elementi presenti e futuri nel selettore.

$ ('div'). Live (function() {});

3

Il plug-in jQuery LiveQuery sembra essere quello che la maggior parte delle persone utilizza per risolvere questo problema.

live Query utilizza la potenza di selettori di jQuery da eventi di legame o cottura callback per gli elementi corrispondenti auto-magicamente, anche dopo che la pagina è stata caricata e il DOM aggiornato.

Ecco un rapido jsfiddle che ho messo insieme per dimostrare questo: http://jsfiddle.net/87WZ3/1/

Ecco una demo di sparare un evento ogni volta che viene creato un div e scrivendo l'ID univoco del div che è stato appena creato: http://jsfiddle.net/87WZ3/2/

+1

Questo era esattamente quello che stavo cercando !!! THX – user357034

3

ho avuto questo stesso problema, così sono andato avanti e ho scritto un plugin per esso: https://gist.github.com/4200601

$(selector).waitUntilExists(function);

Codice:

(function ($) { 

/** 
* @function 
* @property {object} jQuery plugin which runs handler function once specified element is inserted into the DOM 
* @param {function} handler A function to execute at the time when the element is inserted 
* @param {bool} shouldRunHandlerOnce Optional: if true, handler is unbound after its first invocation 
* @example $(selector).waitUntilExists(function); 
*/ 

$.fn.waitUntilExists = function (handler, shouldRunHandlerOnce, isChild) { 
    var found  = 'found'; 
    var $this  = $(this.selector); 
    var $elements = $this.not(function() { return $(this).data(found); }).each(handler).data(found, true); 

    if (!isChild) 
    { 
     (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] = 
      window.setInterval(function() { $this.waitUntilExists(handler, shouldRunHandlerOnce, true); }, 500) 
     ; 
    } 
    else if (shouldRunHandlerOnce && $elements.length) 
    { 
     window.clearInterval(window.waitUntilExists_Intervals[this.selector]); 
    } 

    return $this; 
} 

}(jQuery)); 
+0

Funziona alla grande - Grazie Ryan! – Michael