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>
그것은 굉장합니다, 그것은 매력처럼 작동합니다. 고마워요! –