문제

As shown in the demo, dispatchEvent is not working as expected.

http://jsfiddle.net/DerekL/V8uEN/

Key part:

btn.dispatchEvent(
    document.createEvent("MouseEvent")
    .initMouseEvent("click", true, true, window, 0,
        0, 0, 0, 0,
        false, false, false, false,
        0, null)
);

An alert should pop up after 1 second upon loaded, but it is not coming up and an error appears in the console:

Uncaught InvalidStateError: Failed to execute 'dispatchEvent' on 'EventTarget': The event provided is null.

I don't know where's the problem at since I found a demo almost with the exact same code, and it is working but not mine.

도움이 되었습니까?

해결책

btn.dispatchEvent(
    document.createEvent("MouseEvent")
    .initMouseEvent("click", true, true, window, 0,
        0, 0, 0, 0,
        false, false, false, false,
        0, null)
);

Your problem is that initMouseEvent doesn't return anything. You can't combine all of that into one line. You need to break it up.

var mEvent = document.createEvent("MouseEvent");
mEvent.initMouseEvent("click", true, true, window, 0,
    0, 0, 0, 0,
    false, false, false, false,
    0, null);

btn.dispatchEvent(mEvent);

This is how it's done in the demo you linked to.

다른 팁

This works:

var btn = document.querySelector("button");
btn.addEventListener("click", function () {
   alert("Clicked.");
});

setTimeout(function () {
  var mEvent = document.createEvent("MouseEvent");
  mEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

  btn.dispatchEvent(mEvent);
}, 1000);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top