方法 1点击方法
HTMLElement
s 有一个方法click()
https://developer.mozilla.org/en/DOM/element.click
function goToBar() {
document.getElementById('foo').click();
}
方法 2触发合成事件
我想知道为什么 saluce 删除了他的答案。该解决方案是我过去使用过的(当点击只是 IE 时)。也就是说,触发一个合成浏览器事件(不是像 jQuery 那样的假事件click()
)。让我使用这个想法发布一个解决方案......
演示:http: //jsfiddle.net/eyS6x/3/
/**
* Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
* by testing for a 'synthetic=true' property on the event object
* @param {HTMLNode} node The node to fire the event handler on.
* @param {String} eventName The name of the event without the "on" (e.g., "focus")
*/
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9 /** DOCUMENT_NODE */){
// the node may be the document itself
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + +node.tagName + "#" + node.id);
}
if (node.fireEvent) {
// IE-style
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
} else if (node.dispatchEvent) {
// Gecko-style approach is much more difficult.
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click":
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "JSUtil.fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
var bubbles = eventName == "change" ? false : true;
event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
node.dispatchEvent(event);
}
};
document.getElementById('button').onclick = function() {
fireEvent( document.getElementById('link'), 'click');
}