2011-08-28 25 views
6

ページに特定の要素が存在すると、コールバックをコールするためのイベントまたは単純な関数がありますか。 要素が存在するかどうかを確認する方法は問いません。一例としてjQuery要素が存在するイベント

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

私は.live機能を見てみましょうreadyイベントに

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

何をしますか? –

+0

準備完了機能はこのように@Drakeでは動作しません。例としてこのフィドルを見てください:http://jsfiddle.net/YDn5f/ –

答えて

1

を使用して終了。セレクタ内の現在および将来のすべての要素に対して実行されます。

$( 'div')。live(function(){});

3

LiveQuery jQueryプラグインは、この問題を解決するためにほとんどの人が使用しているようです。

ライブクエリは ページがロードされ、DOMが更新された後も、自動魔法のようにマッチした要素のためのコールバックを発射結合事象または でjQueryのセレクタの力を利用しています。

ここで私はこれを実証するために一緒に入れ、迅速jsfiddleです:http://jsfiddle.net/87WZ3/1/

ここでイベントにdiv要素が作成されるたびに発射して作成されたばかりのdivの一意のIDを書き出すのデモです。 http://jsfiddle.net/87WZ3/2/

+1

これはまさに私が探していたものでした! THX – user357034

3

私はこの同じ問題を抱えていたので、私は先に行って、それ用のプラグインを書いた:https://gist.github.com/4200601

$(selector).waitUntilExists(function);

コード:

(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

これは素晴らしい作品です - Ryanに感謝します! – Michael

関連する問題