I have a div
that is returned from an ajax call which contains an a
. I need to click it in javascript, however I cannot find a way that works in both IE6 and FF.
This works in FF but generates an object required error in IE6:
$('#mylink').click();
This works in IE6 but generates a $("#mylink").get(0).click is not a function error in FF.
$('#mylink').get(0).click();
Any ideas on why this is and what kind of so开发者_StackOverflowlution is available?
EDIT:
Using trigger returns the same error as click in IE6:
$('#mylink').trigger('click');
EDIT:
Placing the code in a timer does not change the behavior:
setTimeout(function() {
$('#mylink').click();
}, 100);
EDIT:
As a workaround, this functions. But it would be nice to better understand the issue. This is not a jQuery issue alone (or maybe at all). The IE6 JavaScript error comes out of MicrosoftAjax.js so it has something to do with that.
var anchor = $('#mylink');
if (anchor.get(0).click) {
anchor.get(0).click();
}
else {
anchor.click();
}
The get method returns the DOM element. You shoudl use eq instead.
$('#mylink').eq(0).click();
If $("#mylink").click() isn't found but $("#mylink").get(0).click() is, then could you use this as the basis for a test?
eg
if ($("#mylink").click)
{
$("#mylink").click()
}
elseif ($("#mylink").get(0))
{
$("#mylink").get(0).click();
}
Far from ideal I know but such is the way of things when dealing with IE6
How about using a trigger ?
$("#mylink").trigger('click');
Try:
$('#mylink').trigger('click');
Should be the same as your first example, though... Do some alerts in IE to make sure the element exists and all that (maybe you have a duplicated ID somewhere or something?).
The object required is likely generated because IE can't find the #mylink
selector in time. Make sure you do the call in the success callback function or provide a timeout function that checks if the element is available before triggering the click:
window.setTimeout(function() {
if ($("#mylink").length) {
$("#mylink").trigger('click');
return false;
}
window.setTimeout(arguments.callee, 1);
},1);
精彩评论