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