如何使用jQuery手动触发委托事件? [英] How do I manually trigger a delegated event with jQuery?

查看:358
本文介绍了如何使用jQuery手动触发委托事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery是否有办法手动触发委托的事件处理程序?

Is there a way with jQuery to manually trigger an delegated event handler?

采用以下示例代码:

<div class="container">
  <input type="button" value="Hello">
  <span class="output"></span>
</div>
​
<script>
  $('.container')
    .on('click', '[type=button]', function(e) {
      $(e.delegateTarget).find('.output').text($(this).val());
    })
    .find('[type=button]').triggerHandler('click');​
</script>

(在线: http://jsfiddle.net/TcHBE/)

我期望它会起作用,并且文本"Hello"将出现在跨度中,而无需实际单击按钮,但是没有.

I was expecting that this would work, and text "Hello" would appear in the span without actually clicking the button, but it doesn't.

我在处理程序中使用了e.delegateTarget,因为除了.container内的某些位置之外,.ouput元素与按钮之间没有已知的关系.这就是为什么我首先使用委托事件处理程序的原因.

I'm using e.delegateTarget inside the handler, because the .ouput element won't be in a known relationship to the button, other than some place inside the .container. That is why I'm using a delegated event handler in the first place.

更新:

我也正在使用triggerHandler,因为该事件在我不想触发的真实代码中具有默认行为. (在真实代码中,该事件是 Bootstrap Modal插件的自定义事件hide,但我在页面加载时触发事件处理程序时,实际上并不想隐藏模式.

Also I'm using triggerHandler, because the event has a default behaviour in the real code I don't want to trigger. (In the real code the event is the custom event hide of the Bootstrap Modal plugin, but I don't actually want to hide the modal when triggering the event handler on page load).

我可以将处理程序提取到一个命名函数中,然后直接调用它,但是由于使用了e.delegateTarget,这会使构造方式更加复杂.

I could extract the handler into a named function and call it directly, but due to the use of e.delegateTarget, that would make the how construct more complicated.

推荐答案

您可以手动创建一个Event对象,并相应地设置target属性,以使jQuery认为该事件已冒出.

You could create an Event object manually and set the target property accordingly to trick jQuery into thinking the event bubbled up.

var c = $('#container');

c.on('click', '[type=button]', function(e) {
    $(e.delegateTarget).find('span').text($(this).val());
});

var event = jQuery.Event('click');
event.target = c.find('[type=button]')[0];

c.trigger(event);

http://jsfiddle.net/PCLFx/

这篇关于如何使用jQuery手动触发委托事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆