Trigger events on content

I wrote a Chrome Extension that automatically fills some registration forms. There are some select fields that need to be triggered on " change " event in order to start some Ajax calls.

First I use JQuery attr or val to change the value of the select field, and than I use .trigger to invoke the "change" event, but this last one doesn't work.

Example:

I want to select the option that contains the word "London" and invoke the change element in order to start some operations of the native code that have some listeners on "change" event

jQuery("#SelectElement option:contains('London')").attr("selected", "selected"); 
jQuery("#SelectElement").trigger("change"); <--- not works

I tried also:

jQuery("#SelectElement option:containt('London')").attr("selected", "selected").change();

But if I try this code on console , it works.

Suggestions?


In my case,

var event = new CustomEvent('change');

did not work.

I had to initialize the event like this:

var evt = document.createEvent("HTMLEvents");
evt.initEvent("keyup", true, true);

First arg 'bubbles' should be true so the event should bubble up through the event chain.

event.initEvent(type, bubbles, cancelable);

Source: https://developer.mozilla.org/en-US/docs/Web/API/Event/initEvent


I had the same problem and as far as I know it's because of something called framework event listeners. that you cannot trigger from your code by jquery! but the solution is trigger the event this way:

$(selector)[0].dispatchEvent(new Event("eventName"))

链接地址: http://www.djcxy.com/p/22114.html

上一篇: 以普通英语列出的项目的正则表达式

下一篇: 触发内容事件