简体   繁体   中英

Trigger Event Javascript IE

I got a simple problem and can't get it working: I'm trying to trigger an event in IE 7. To do this, I tried following:

if (typeof fireEvent != 'function') {
    function fireEvent(target, evt) {
        if (document.createEvent) {
            var clickEvent = document.createEvent("MouseEvents");
            clickEvent.initMouseEvent(evt, true, true, window,
                0, 0, 0, 0, 0, false, false, false, false, 0, null);
            return target.dispatchEvent(clickEvent);
        }
        else {
            return target.fireEvent("on" + evt);
        }
    }
}

However, this doesn't work. The event isn't triggered in IE 7. Jquery trigger will work in IE 7, however, I can't use it, because it's creating a memory leak in my Java application (approx 400MB memory leak) and the script is dying because of this.

What I've tried is a simple login with Javascript like that ( http://accounts.google.com/ ):

document.getElementById('Email').value = "%s";
document.getElementById('Passwd').value = "%s";
var signIn = document.getElementsByName('signIn')[0];
fireEvent(signIn, "click");

Both fields ("Email" and "Passwd") are getting filled, but the form isn't submitted. As an alternative I tried using the "onsubmit" event. The last 2 lines can be changed to:

var gaiaLoginForm = document.getElementById("gaia_loginform");
fireEvent(gaiaLoginForm, "submit");

Once more: jQuery and any other big framework aren't useable!

You can't just "fire" an event like that in older IE. You have to tell the browser what you're trying to trigger, not only the type. The point is that you can change the property values of the object before firing it. Try this:

var evtObj = document.createEventObject();
target.fireEvent("on" + evt, evtObj);

Also, I'd suggest to investigate on the causes of your alleged memory leak.

(By the way, Javascript != Java.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM