I'm trying to use the objects within my jQuery code.
I've nearly this:
var opts = {
ul: $(this).find('.carousel'),
li: ul.find('li')
}
li
property gives an error Cannot call method 'find' of undefined
How can it be fixed?
It doesn't matter what your selector is, you can't access a property of an object that you are declaring, while you are declaring it.
Why would ul
be declared? You're making a property ul
on your opts
object.
What you might want is:
var opts = {
ul: $(this).find('.carousel')
}
opts.li = opts.ul.find('li');
But if you don't actually need references to both groups then:
var opts = {
li: $(this).find('.carousel li')
}
is just as good.
You could also do:
var $carousel = $(this).find('.carousel');
var options = {
carousel: $carousel,
carouselItems: $carousel.find('li')
}
var CarouselOptions = (function () {
var options = function (carousel) {
this.carousel = $(carousel);
this.carouselItems = this.carousel.find('li');
};
options.prototype.myOptionsFunction = function () {
// Don't know what you want your object to do, but you wanted a prototype...
};
return options;
})();
var opts = new CarouselOptions($(this).find('.carousel'));
(Be careful with what your this
is, presumably you have more than one .carousel
element on the page, and here you want the one that is within the target of an event.)
Your error message is essentially saying that $(this)
is undefined (or in other words, jQuery couldn't find this element). Because you don't have any code other than the single object you are trying to set, I don't know what the actual value of this
is.
What I would do is ensure that this
is set to an element of some sort. A simple console.log(this)
should handle that. If this
isn't an HTML element, then that's your problem. Either ensure you are inside of a jQuery event function like this:
$('#id').click(function() {
this === document.getElementById('id'); // true
});`
Or you can just drop the $(this)
:
var opts = {};
opts.ul = $('.carousel'),
opts.li = opts.ul.find('li')
var that = $(this);
var opts = {
ul: that.find('.carousel'),
li: ul.find('li')
}
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.