[英]Can I get usable data in a jQuery live handler for a custom event?
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>
看起来最简单的方法可能是使用http://docs.jquery.com/Events/trigger#eventdata上一个“替代”示例中描述的格式。 该示例使用对象文字来指定事件对象,您可以在其中创建自定义属性。 我也尝试了上面介绍的方法,但没有用,但是其他格式对我有用。 所以不要打电话
$(this).trigger('custom', ['Times clicked: ' + clicks ])
尝试
$(this).trigger({type:'custom', clicks: clicks});
然后通过以下方式在“自定义”事件的事件处理程序中引用它:
"Times clicked: " + e.clicks;
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.