如何使用 jQuery 手动触发委托事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12724147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:57:33  来源:igfitidea点击:

How do I manually trigger a delegated event with jQuery?

jquery

提问by RoToRa

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

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

Take following example code:

采取以下示例代码:

<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>

(Online: http://jsfiddle.net/TcHBE/)

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

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

我期待这会起作用,并且文本“Hello”会出现在跨度中,而无需实际单击按钮,但事实并非如此。

I'm using e.delegateTargetinside the handler, because the .ouputelement 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.

e.delegateTarget在处理程序内部使用,因为.ouput元素不会与按钮存在已知关系,除了.container. 这就是我首先使用委托事件处理程序的原因。

Update:

更新:

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 hideof the Bootstrap Modal plugin, but I don't actually want to hide the modal when triggering the event handler on page load).

我也在使用triggerHandler,因为该事件在我不想触发的真实代码中具有默认行为。(在实际代码事件是自定义事件hide中的引导模态插件,但我其实不愿意触发页面加载事件处理函数时隐藏模式)。

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.

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

回答by Prinzhorn

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

您可以手动创建一个 Event 对象并相应地设置该target属性以欺骗 jQuery 认为该事件冒泡了。

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/

http://jsfiddle.net/PCLFx/

回答by Akash

We can pass an additional event configurationto jQuery's $.Event()as the second argument. More information here.

我们可以传递一个额外的event configurationtojQuery's $.Event()作为second argument. 更多信息在这里

$('#click-me').on('click', function(evt){
  $(document).trigger($.Event('custom-click', {target: evt.currentTarget}));
});

$(document).on('custom-click', '#click-me', function(evt){
  alert(`${evt.type} was triggered on button with ${evt.target.id} id.`);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="click-me">Click Me</button>

Good Luck...

祝你好运...

回答by cars10m

I know, this question is ancientbut as I was stumbling over it while looking for an answer to another problem I thought I might as well share my slightly simpler approach here.

我知道,这个问题很古老,但是当我在寻找另一个问题的答案时绊倒它时,我想我不妨在这里分享我稍微简单的方法。

The idea is to simply create the event on the desired target elementdirectly: $(target_selector).trigger(event_type)or - even shorter for standard events like "click" - do $(target_selector).click(), see my little fiddle below:

这个想法是简单地直接在所需的目标元素上创建事件:$(target_selector).trigger(event_type)或者 - 对于像“click”这样的标准事件甚至更短 - do $(target_selector).click(),请参阅下面的小小提琴:

$(function(){
 $('.container').on('click','button',function(){
  console.log('delegated click on '+$(this).text());
  return false;
 });
 $('#other').click(e=>$('.container button').trigger('click'));
 $('#clickone').click(e=>$('.container .one').click());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container">
<button type="submit" class="one">click 1</button> and another chance to click here on <button class="two">click 2</button>.
</form><br>
<div id="other">Trigger clicks on both buttons here!</div><br>
<div id="clickone">Trigger a click on button "one" only.</div>

回答by bldoron

Selectors in the .on()method are optional.
When you write:

.on()方法中的选择器是可选的。
当你写:

  $('.container')
    .on('click', '[type=button]', function(e) {
      $(e.delegateTarget).find('.output').text($(this).val());
    })
    .find('[type=button]').triggerHandler('click');?

You are telling the event handler to listen only to the button click inside the container.
$(e.delegateTarget)is just a reference to the outer container.

您告诉事件处理程序只侦听容器内的按钮单击。
$(e.delegateTarget)只是对外部容器的引用。

I've updated your fiddle to echo this.

我已经更新了你的小提琴来回应这个

This is a quote from the API:

这是来自 API的引用

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

当提供选择器时,事件处理程序被称为委托的。当事件直接发生在绑定元素上时,不会调用处理程序,而是仅针对与选择器匹配的后代(内部元素)调用处理程序。jQuery 将事件从事件目标冒泡到附加处理程序的元素(即从最里面到最外面的元素),并为沿该路径匹配选择器的任何元素运行处理程序。

回答by Ahmad

As a complementary to @Prinzhorn's answer, it may be useful to have this JQuery function:

作为对@Prinzhorn 的回答的补充,拥有这个 JQuery 函数可能很有用:

(function( $ ){
    $.fn.triggerParent = function (eventName, parent) {
        this.each(function() {
            var event = jQuery.Event(eventName);
            event.target = this;
            $(parent).trigger(event);
        });
    };
})( jQuery );