I want to simulate a click to an anchor tag with all extras like correct target handling.
There seems to be a "[click()][3]" method for anchor's DOM object but not all browsers support that. Firefox throws this error:
Error: anchorObj.click is not a function
It also works strangely on Opera 10 and Konqueror, causing infinite clicks to happen when it's called inside onclick handler of a surrounding div. I guess only IE8 works fine with it. Anyway I don't want it since major browsers mostly have problems with it.
I found this alternate solution for Firefox in Mozilla forums:
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
anchorObj.dispatchEvent(evt);
This seems too ugly and cumbersome for me. I don't know how compatible it is and I want to avoid writing browser specific code as much as possible.
I can't use location.href = anchorObj.href; because it doesn't handle "target" attribute. I can do some hard coding based on target's value but I'd like to avoid that as well.
There is suggestion of switching to JQuery but I'm not sure how well it handles target property either since I haven't worked with it before.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…