admin管理员组

文章数量:1323715

I'm getting error Cannot read property 'click' of undefined. I'm currently trying to automate/emulate a click function using the code below.

$('.trigger-pdf')[0].click();

I believe the error happens if javascript cannot find the selector in the markup/DOM or if it does not exist. Is there a way to resolve an error like this.

I'm getting error Cannot read property 'click' of undefined. I'm currently trying to automate/emulate a click function using the code below.

$('.trigger-pdf')[0].click();

I believe the error happens if javascript cannot find the selector in the markup/DOM or if it does not exist. Is there a way to resolve an error like this.

Share Improve this question asked Nov 8, 2017 at 4:12 clestcruzclestcruz 1,1113 gold badges34 silver badges80 bronze badges 1
  • post your related html code too – Shankar Commented Nov 8, 2017 at 4:19
Add a ment  | 

3 Answers 3

Reset to default 2

As I understand, you want to call the click event on that specific element dynamically through your code.

Your $('.trigger-pdf') doesn't exist at the time you call .click()

So first, you need to make sure it exists by something like this:

if ($.type($('.trigger-pdf')) !== 'undefined' && $('.trigger-pdf').length > 0) {
       $('.trigger-pdf').trigger('click');
}

If your element (.trigger-pdf) is something that was dynamically added to the DOM, then binding an event with .on() wouldn't help you. You need to use dynamic binding as follows:

$('body').on('click','.trigger-pdf',function() { // Do your stuff here...});

Instead of $('body'), refer to something that is physically there when your code runs.

You can make your code more robust by using

$('.trigger-pdf').eq(0).click()

which won't trigger any errors if the element doesn't exist.

See https://api.jquery./eq/


You should figure out why that appears to be the case though. Perhaps you should be wrapping your code in a document ready event handler, ie

jQuery(function($) {
  $('.trigger-pdf').eq(0).click()
})

Always use on() to bind events

$('static_element').on('click', '.dynamic_element', function() { // code });

本文标签: