尝试在选择器的迷你对象中使用 .find() 和 .children 时遇到困难

having difficulty trying to use .find() and .children inside a mini object of selectors

本文关键字:find children 遇到 选择器 对象      更新时间:2023-09-26

我基本上试图摆脱过程式js方法,因此尝试更多地使用对象。我已经在我的整个对象中设置了一个对象来缓存选择器并设置变量等,但我似乎遇到了问题。目前,当我运行此代码时,我收到 2 个错误,告诉我 .length 和 .children 都是未定义的。有人可以解释设置这些的正确方法,以便可以使用jquery方法吗?

.JS

var bop = {
        els: {
           // cache selectors ...
            grid: $( '#grid' ),
            box: this.grid.children(),
            box_l: this.box.length,
            start_btn: $( '#start' ),
            counter: $( '#counter' ),
            sequence: 5            
        }
}

如果你期望this引用你正在使用对象文字构建的正在构建的对象,那么这就是你的问题。JavaScript不是这样工作的。

您可以这样做:

var bop = {
 els: {
   grid: $('#grid'),
   // ...
 }
};
bop.els.box = box.els.grid.children();
// etc

this引用完全是关于函数调用的,实际上与对象无关,或者不像你来自 C++/C#/Java 背景时想象的那么多。

在文本对象中使用 this 时,它不引用正在创建的对象,它仍然与文本对象外部的代码相同。

如果您

非常想使用this,请将缓存对象更改为

els: {
           // cache selectors ...
            grid: $( '#grid' ),
            box: function(){
                   return this.grid.children()
            },
            box_l: function(){
                  return this.box().length
            },
            start_btn: $( '#start' ),
            counter: $( '#counter' ),
            sequence: 5            
        }

其他明智的做法是确保在使用boxbox_1属性时引用$( '#grid' )

附带说明一下,这个小提琴将帮助您理解为什么您的this不能按照您认为的方式工作。干杯。