简体   繁体   中英

'undefined' function when triggering a click of a link with jQuery

For some reason this works in FF 11, Chrome, and even in IE but not in FF 3.6 or Safari 5.

Basically I'm triggering the click of a link with:

var $currentItem = $('#' + currentId);
var modalSeriesList = $('.js-modal-series');
var index = modalSeriesList.index($currentItem);
var $nextItem = modalSeriesList[index + 1];

var nextClick = function() {
    $(document).off('keydown.general');
    $nextItem.click();
}

$(document).off('keydown.general');

if ($nextItem) {
    $nextButton.click(nextClick);
}​

But when I click on the link in FF 3.6 or Safari 5 I get the following error:

TypeError: 'undefined' is not a function (evaluating '$nextItem.click()')

Is there any particular "gotcha" that I don't know about here using the following method?

Try .eq() so $nextItem is a jQuery collection:

var $nextItem = modalSeriesList.eq(index + 1);

// ...

$nextItem.click()

Using [...] retrieves the DOM Object, which doesn't have a .click() method.

You could try

if( typeof $nextItem == 'undefined' ){
    $nextButton.trigger('click');
}

instead of

if ($nextItem) {
    $nextButton.click(nextClick);
}​

if you turn condition of if statement into

if(typeof $nextItem == 'undefined' )

it works. As Porco said probably $nextItem does not exist....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM