开发者

what's the equivalent of jquery's 'trigger' method without jquery?

what's the equivalent of jQuery's trigger method without jQuery?

e.g., how do i do something like $('.blah').trigger('click'); without jQuery开发者_如何学运维?


event.initMouseEvent("click"...

Here is an example:

function simulateClick(elId) {
    var evt;
    var el = document.getElementById(elId);
    if (document.createEvent) {
        evt = document.createEvent("MouseEvents");
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    (evt) ? el.dispatchEvent(evt) : (el.click && el.click());
}

var foo = document.getElementById("hey");

foo.onclick = function () {alert("bar");}

simulateClick("hey");


For some value of "a very shoddy equivalent":

var button = document.getElementById("thebutton")
button.click()

Not all browsers (e.g. Firefox!) allow simulated events this way! Using onclick() only works if the event is in-line, etc.

Please see the jQuery source and search for "trigger:" (first match) to see all the icky stuff done to "make it work" (a good bit of it is just munging around the jQuery internals, other frameworks make have much simpler examples).

Happy coding.


in Javascript

var event = document.createEvent("Event");
event.initEvent("click", false, true); 
document.getElementById("blah").dispatchEvent(event);

is equivalent for jQuery trigger as below

$('#blah').trigger('click');


Here is my example. Working perfectly in all situations

var d=document.createEvent("MouseEvents"),
    c=document.createEvent("MouseEvents"),
    p=document.createEvent("MouseEvents");
    d.initMouseEvent("mousedown",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
    c.initMouseEvent("click"    ,true,true,window,0,0,0,0,0,false,false,false,false,0,null);
    p.initMouseEvent("mouseup"  ,true,true,window,0,0,0,0,0,false,false,false,false,0,null);

    var element =// some selector;

    element.dispatchEvent(d);
    element.dispatchEvent(c);
    element.dispatchEvent(p);


TL;DR: create an Event Object and pass it to element.dispatchEvent(event)

function simulateClick() {
  const event = new MouseEvent('click', {
    view: window,
    bubbles: true,
    cancelable: true
  });
  const element = document.getElementById('checkbox');
  element.dispatchEvent(event);
}

More info https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#triggering_built-in_events

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜