简体   繁体   English

jQuery .on触发事件侦听器

[英]jQuery .on trigger event listener

There is a best practice to invoke a jQuery change handler immediately afters its definition to re-use the code and initialise the GUI, like 最佳做法是在定义后立即调用jQuery更改处理程序,以重新使用代码并初始化GUI,例如

$("#mySelect").change(function() {
  $("#myTextField").val( $(this).text());
}).change(); // here the element is immediately triggered, so one does not need a separate code path for the init-case

Without the immediate call using .change() the GUI would not reflect the initial value of #mySelect in #myTextfield. 没有使用.change()的立即调用,GUI将不会在#myTextfield中反映#mySelect的初始值。

With newer versions of jQuery I would like to use event-delegation and do the same stuff using the .on() API. 对于较新版本的jQuery,我想使用事件委托,并使用.on() API做同样的事情。

$("#myForm").on('change', '#mySelect', function() {
  $("#myTextField").val( $(this).text());
}).change();

This does not work anymore, because the .change() is not triggered on the right element and not with the right event.target, so jQuery can't call my event handler. 这不再起作用,因为.change()不会在正确的元素上触发,也不会在正确的event.target上触发,因此jQuery无法调用我的事件处理程序。

This works, but does no longer reflect the best practice without the separate init code-path: 这有效,但是如果没有单独的init代码路径,则不再反映最佳实践:

$("#myForm").on('change', '#mySelect', function() {
  $("#myTextField").val( $(this).text());
});
$("#mySelect").change();

Question: Any good way to solve this, without re-selecting the element and triggering the event? 问题:有什么好方法可以解决此问题,而无需重新选择元素并触发事件?

You would need to find all the elements and call trigger on them... Because delegation delegates the handling to some other element up the DOM (as you likely know) 您将需要找到所有元素并在其上调用触发器...因为委派将处理委托给DOM上的其他元素(您可能知道)

You would essentially have to do what you have done in your 3rd example. 从本质上讲,您将必须做在第三个示例中所做的事情。 I know of no other way to achieve this. 我知道没有其他方法可以实现这一目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM