在Javascript代码,我想以编程方式导致浏览器打开链接这是我的网页上。 简单的例子:
<a id="foo" href="mailto:somebody@example.com">something</a>
function goToBar() {
$('#foo').trigger('follow');
}
这是假设的,因为它没有实际的工作。 不,触发click
不这样做。
我知道window.location
和window.open
,但这些来自本地不同链接跟随在某些方面是对我很重要:a)在存在<base />
元素,和b)的情况下, mailto
的网址。 尤其后者是显著。 在Firefox至少致电window.location.href = "mailto:somebody@example.com"
导致窗口的unload
处理火,而只需点击一个mailto
链接没有,据我可以告诉。
我正在寻找一种方式来触发浏览器的默认链接处理,从JavaScript代码。
难道这样的机制存在吗? 具体的工具包,答案也欢迎(特别是壁虎)。
据我所知,确实window.location的您正在寻找的到底是什么,引发了浏览器的默认链接点击行为。
有些浏览器发现任何事件被解雇或实际HREF改变之前的协议。
window.location = "mailto:somebody@example.com";
下面想我得到下面的结果中提到的小提琴演示:
- 铬:火
onbeforeunload
与按钮和链接 - 火狐火灾
onbeforeunload
只为按钮 - Safari浏览器:永远不会触发
onbeforeunload
- 歌剧:同Safari浏览器
因此,要防止一个很好的方式unload
事件被解雇是通过返回假beforeunload
。
方法1单击方法
HTMLElement
■找一个方法, click()
https://developer.mozilla.org/en/DOM/element.click
function goToBar() {
document.getElementById('foo').click();
}
方法2触发合成事件
我不知道为什么saluce删掉了他的答案。 该解决方案是什么,我已经在过去使用(当点击是一个IE唯一的事情)。 也就是说,发射合成的浏览器事件(不是假像一个jQuery的click()
让我发布使用这种想法的解决方案...
DEMO: 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');
}