jQuery 现在允许您使用live来处理自定义事件,这是我在最近的项目中使用过的,并且发现非常方便。但是,我遇到了一个限制/错误,我希望有人能够帮助我。
当您触发一个事件时,您也可以传递额外的数据数组,如下所示:
$(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>