简体   繁体   English

无法调用未定义的方法“查找”

[英]Cannot call method 'find' of undefined

I'm trying to use the objects within my jQuery code. 我正在尝试在jQuery代码中使用对象。

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 li属性给出错误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? 为什么要宣布ul You're making a property ul on your opts object. 您正在对opts对象创建属性ul

Ugly: 丑陋:

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: 但是,如果您实际上不需要同时引用这两个组,则:

Cleaner: 清洁器:

var opts = {
    li: $(this).find('.carousel li')    
}

is just as good. 一样好

Cleanest: 最干净的:

You could also do: 您也可以这样做:

var $carousel = $(this).find('.carousel');
var options = {
    carousel: $carousel,
    carouselItems: $carousel.find('li')
}

Godawful, but you asked for it: 天哪,但您要求它:

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'));

Also

(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.) (请特别注意this是什么,假设页面上有多个.carousel元素,并且在此您希望该元素位于事件目标之内。)

Your error message is essentially saying that $(this) is undefined (or in other words, jQuery couldn't find this element). 您的错误消息实际上是在说$(this)是未定义的(换句话说,jQuery找不到此元素)。 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. 因为你根本就没有你想设置单个对象之外的任何代码,我不知道是什么的实际价值this是。

What I would do is ensure that this is set to an element of some sort. 我要做的是确保将this设置为某种元素。 A simple console.log(this) should handle that. 一个简单的console.log(this)应该可以解决这个问题。 If this isn't an HTML element, then that's your problem. 如果this不是HTML元素,那就是您的问题。 Either ensure you are inside of a jQuery event function like this: 确保您位于jQuery事件函数中,如下所示:

$('#id').click(function() { 
    this === document.getElementById('id');  // true
});`

Or you can just drop the $(this) : 或者,您可以只删除$(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')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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