[英]jquery object inside an object literal
i am trying not to repeat the selector and get to its children via a the same objects parentElment
declared variable. 我试图不重复选择器,并通过相同的对象parentElment
声明的变量到达其子级。
I tried: 我试过了:
testimonialsBelt={
parentElment:$(".testimonialsCntnr ul"),
childrenElem:this.parentElment.children().length
}
I also tried: 我也尝试过:
testimonialsBelt={
parentElment:$(".testimonialsCntnr ul"),
childrenElem:$("testimonialsBelt.parentElment").children().length
}
but i keep on getting a undefined
when calling alert(testimonialsBelt.childrenElem)
. 但是在调用alert(testimonialsBelt.childrenElem)
时,我一直undefined
得到undefined
。
this
and when must i have the full path? 什么时候可以使用this
,什么时候必须使用完整路径? (in this case testimonialsBelt.parentElment
). (在这种情况下为testimonialsBelt.parentElment
)。 i am trying to have all these variables in one object called testimonialsBelt. 我试图将所有这些变量放在一个称为testimonialsBelt的对象中。 i know i can do this with loose javaScript. 我知道我可以用松散的JavaScript做到这一点。 Thanks 谢谢
In object literals, you can only use this
to refer to the object that you're declaring inside of a function. 在对象文字中,您只能使用this
来引用要在函数内部声明的对象。 Try the following: 请尝试以下操作:
var testimonialsBelt = {
parentElment: $(".testimonialsCntnr ul"),
childrenElem: function() {
return this.parentElment.children().length;
}
};
The difference in calling childrenElem is that instead of using alert(testimonialsBelt.childrenElem)
, you would instead have alert(testimonialsBelt.childrenElem())
. 呼吁childrenElem不同的是,而不是使用alert(testimonialsBelt.childrenElem)
你就不是有alert(testimonialsBelt.childrenElem())
Otherwise, this
refers to the current scope that you are in (typically window if you are declaring the object literal as a global). 否则, this
是指您当前所在的作用域(如果将对象文字声明为全局变量,则通常为窗口)。
Addressing your edit: I'm not sure what you mean by "loose javascript," but I assume you mean as simple as possible. 解决您的修改:我不确定“宽松的javascript”是什么意思,但我认为您的意思尽可能简单。 In which case, you can try the following, although I'm not a big fan of the method. 在这种情况下,尽管我不太喜欢该方法,但是您可以尝试以下方法。 It's more verbose, but is easy to understand. 它比较冗长,但易于理解。
var testimonialsBelt = {
parentElment: $(".testimonialsCntnr ul")
};
testimonialsBelt.childrenElem = parentElment.children().length;
This gives you an object where childrenElem
is static (it doesn't change) and avoids calling $(".testimonialsCntnr ul")
twice. 这为您提供了一个对象,其中childrenElem
是静态的(不变),并且避免了两次调用$(".testimonialsCntnr ul")
。 However, if you expect $(".testimonialsCntnr ul").children()
to change, then you will need to use my first example. 但是,如果您期望$(".testimonialsCntnr ul").children()
发生更改,那么您将需要使用我的第一个示例。
In JavaScript (not ECMAScript) you can use this: 在JavaScript(而非ECMAScript)中,您可以使用以下代码:
testimonialsBelt={
parentElment:#1=$(".testimonialsCntnr ul"),
childrenElem:#1#.children().length
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.