2009-10-01 1 views
3

jQuery를 사용하면 live을 사용하여 최신 이벤트에 사용한 사용자 지정 이벤트를 처리 할 수 ​​있으며 매우 편리합니다. 그러나 나는 누군가가 나를 도울 수 있기를 바라고있는 제한/버그에 맞서 왔습니다. 당신이 이벤트를 트리거 할 때 사용자 정의 이벤트에 대한 jQuery 라이브 핸들러에서 유용한 데이터를 가져올 수 있습니까?

, 당신은 이런 식으로도 데이터를 추가로 배열을 전달할 수 있습니다

$(this).trigger('custom', ['foo', 'bar' ]); 

그냥 bind을 사용한 경우, 당신은 절대적으로 이러한 변수에 액세스 할 수 있습니다. 그러나 라이브를 사용하는 경우 데이터 에 액세스 할 수 없다는 것을 알게되면을 알 수 있습니다. 내가 잘못? 다른 방법이 있습니까?

$().ready(function() { 

    $('button').click(function(){ 
     $('<li>Totally new one</li>').appendTo('ul'); 
    }); 

    $('li').bind('custom', function(e, data) { 
     // this one works fine for old elements, but not for new ones 
     $('#output1').text('Bind custom from #' + e.target.id + '; ' + data); 
    }).live('custom', function(e, data) { 
     // this one triggers for old and new elements, but data is useless 
     $('#output2').text('Live custom from #' + e.target.id + '; ' + data); 
    }).live('click', function(){ 
     $('div').text(''); 
     // just using click count to illustrate passing data in the trigger 
     var clicks = $(this).data('clicks'); 
     if(typeof clicks == 'undefined') clicks = 1; 
     $(this).trigger('custom', ['Times clicked: ' + clicks ]).data('clicks', clicks + 1); 
    }); 
}); 

및 관련 HTML : : 그것은 가장 쉬운 방법처럼 보인다

<button>Add</button> 
<ul> 
    <li id="one">First Item</li> 
    <li id="two">Second Item</li> 
    <li id="three">Third Item</li> 
</ul> 
<div id="output1">Result 1</div> 
<div id="output2">Result 2</div> 

답변

2

마지막 "대체"에 설명 된 형식을 사용할 수 있습니다 여기에

몇 가지 데모 설명하는 코드 예 : http://docs.jquery.com/Events/trigger#eventdata. 이 예제는 객체 리터럴을 사용하여 사용자 정의 속성을 만들 수있는 이벤트 객체를 지정합니다. 위에서 설명한 접근 방법을 사용하지 않으려 고했지만 대체 형식이 유용합니다. 그래서 그 대신

를 호출
$(this).trigger('custom', ['Times clicked: ' + clicks ]) 

$(this).trigger({type:'custom', clicks: clicks}); 

을 시도하고 다음을 통해 "사용자 정의"이벤트의 이벤트 처리기에서이를 참조 : 도움이

"Times clicked: " + e.clicks; 

희망!

+0

그것은 굉장합니다, 그것은 매력처럼 작동합니다. 고마워요! –

관련 문제