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
3 Answers
Reset to default 2As 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 });
本文标签:
版权声明:本文标题:javascript - Getting an error "Cannot read property 'click' of undefined" if selector or class 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742124842a2421890.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论