Why JQuery doesn't trigger added eventlistener?

时光总嘲笑我的痴心妄想 提交于 2019-12-23 03:10:37

问题


I have recognized, that eventhandler added with addEventListener where not influenced by $.trigger. The special reason for that question is, that I have several self created html elements which implements some logic without using external libraries (only pure js). Now in my main project I want to use these controls and further there I have external libaries like jQuery. Now for example I want to trigger the change event (remember...events are added with element.addEventListener("event", function)) with $(element).trigger("change").

Result: nothing happened

The event only is triggered, when i use code like this:

event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
event.eventName = 'change';
element.dispatchEvent(event);

On the other side...eventhandler added with jQuery, where also triggered by a custom created event.

Now the magic question: Why??

You can find a little example in the following jsfiddle. http://jsfiddle.net/UYyXv/3/


回答1:


I have got an explanation from the jquery forums.

jQuery events are a level higher than the native events. Trigger fakes a jQuery event. If you want to fake a native event you need to call it as you wrote in the question.

Simple answer, don’t use native events.

JΛ̊KE




回答2:


why don't you just try

$(SELECTOR).change(function(e){
    e.preventDefault();
    //***DO STUFF HERE***
})


来源:https://stackoverflow.com/questions/14232448/why-jquery-doesnt-trigger-added-eventlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!