前段时间我遇到了与自定义事件相同的问题,并通过使用在另一个问题中找到的代码来解决:
Custom events in IE without using libraries
实际上你不需要使用所有的代码,它们是 3 个函数用作浏览器兼容性的包装器。
但我也建议您使用 .click 方法,它可以更轻松地解决您的问题(至少对于正常点击而言)
http://www.w3schools.com/jsref/met_html_click.asp
所以就这样做
document.getElementById("loginButton").click();
我在这里粘贴来自另一个问题的sergey gospodarets的代码,这可能很有用。
function triggerEvent(el,eventName){
var event;
if(document.createEvent){
event = document.createEvent('HTMLEvents');
event.initEvent(eventName,true,true);
}else if(document.createEventObject){// IE < 9
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
if(el.dispatchEvent){
el.dispatchEvent(event);
}else if(el.fireEvent && htmlEvents['on'+eventName]){// IE < 9
el.fireEvent('on'+event.eventType,event);// can trigger only real event (e.g. 'click')
}else if(el[eventName]){
el[eventName]();
}else if(el['on'+eventName]){
el['on'+eventName]();
}
}
function addEvent(el,type,handler){
if(el.addEventListener){
el.addEventListener(type,handler,false);
}else if(el.attachEvent && htmlEvents['on'+type]){// IE < 9
el.attachEvent('on'+type,handler);
}else{
el['on'+type]=handler;
}
}
function removeEvent(el,type,handler){
if(el.removeventListener){
el.removeEventListener(type,handler,false);
}else if(el.detachEvent && htmlEvents['on'+type]){// IE < 9
el.detachEvent('on'+type,handler);
}else{
el['on'+type]=null;
}
}
var _body = document.body;
var customEventFunction = function(){
alert('triggered custom event');
}
// Subscribe
addEvent(_body,'customEvent',customEventFunction);
// Trigger
triggerEvent(_body,'customEvent');