What causes TypeError: undefined is not a function?
All, I've got some code that I'm trying to debug and I used the following bit of code in my JS console:
clickEvents = $('ul.breadcrumb[data-allownextonly]').data("events").click;
jQuery.each(clickEvents, function(key, value) {
console.log(value.handler);
})
When I execute this I get the error: TypeError: undefined is not a function
My question is what causes this to happen? From most of the things I read it deals with the fact that jQuery isn't loaded properly or there is a conflict between two scripts. jQuery is loading properly because I have other objects on my page that jQuery is working fine on. I'm using Wordpress so there is already no conflict.
In my console I changed my JS debugging to something like this:
clickEvents = jQuery('ul.breadcrumb[data-allownextonly]').data("events").click;
jQuery.each(clickEvents, function(key, value) {
console.log(value.handler);
})
When I execute this I get the following error: TypeError: Cannot read property 'click' of undefined
Can anyone let me know what other reasons I would be getting these errors? If I have a conflicting script or something along those lines, how can I find out where the conflict is?
Thanks!
According to the jQuery API, the .data( key )
method returns undefined if the matched element doesn't have any data matching the key. Have a look at its usage http://api.jquery.com/data/. It only operates on the first element in the matched set in any case, so you cant use it to get an array of click event handlers. As is, it is saying that the first matched element has no data attribute "events". Once you get the data that is attached, do
var clickEvents = [];
$( selector ).data( key ).each( function() {
clickEvents.push( $(this).click );
});
to collect the click events.
当您尝试执行未初始化或未正确初始化的函数时,会出现该错误。
It would seem that jQuery('ul.breadcrumb[data-allownextonly]').data("events")
is undefined
, so any dereferencing on that raises an error.
Btw, changing $
to jQuery
won't change much in your code. If jQuery wasn't loaded, it would give a different error.