2011-08-28 2 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/

여기에 이벤트를 사업부가 생성 될 때마다 발사하고 방금 만든 사업부의 고유 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

위대한 작품 - 라이언 감사합니다! – Michael