【问题标题】:jquery object inside an object literal对象文字内的jquery对象
【发布时间】:2009-11-15 19:05:35
【问题描述】:

我试图不重复选择器并通过相同的对象parentElment 声明变量获取其子级。

我试过了:

testimonialsBelt={
    parentElment:$(".testimonialsCntnr ul"),
    childrenElem:this.parentElment.children().length
}

我也试过了:

testimonialsBelt={
    parentElment:$(".testimonialsCntnr ul"),
    childrenElem:$("testimonialsBelt.parentElment").children().length
}

但我在拨打alert(testimonialsBelt.childrenElem) 时不断收到undefined

  1. 有没有办法用对象字面量获取jquery 对象?

  2. 什么是规则?我什么时候可以使用this,什么时候必须有完整路径? (在本例中为 testimonialsBelt.parentElment)。

我试图将所有这些变量放在一个名为 testimonialsBelt 的对象中。我知道我可以用松散的 JavaScript 做到这一点。 谢谢

【问题讨论】:

  • .testimonialsCntnr ul 中的<li>s 的数量会改变吗?这种差异对于确定您的问题需要哪种解决方案非常重要。
  • 不,它不会改变。非常感谢
  • 请参阅下面对我的答案的修改。

标签: javascript jquery object


【解决方案1】:

在对象字面量中,您只能使用this 来引用您在函数内部声明的对象。请尝试以下操作:

var testimonialsBelt = {
    parentElment: $(".testimonialsCntnr ul"),
    childrenElem: function() {
        return this.parentElment.children().length;
    }
};

调用 childrenElem 的不同之处在于,您将使用 alert(testimonialsBelt.childrenElem()),而不是使用 alert(testimonialsBelt.childrenElem)

否则,this 指的是您所在的当前范围(如果您将对象字面量声明为全局,则通常是 window)。

解决您的编辑问题:我不确定您所说的“松散的 javascript”是什么意思,但我认为您的意思是尽可能简单。在这种情况下,您可以尝试以下方法,尽管我不是该方法的忠实粉丝。它比较冗长,但很容易理解。

var testimonialsBelt = {
    parentElment: $(".testimonialsCntnr ul")
};
testimonialsBelt.childrenElem = parentElment.children().length;

这为您提供了一个对象,其中childrenElem 是静态的(它不会改变)并避免调用$(".testimonialsCntnr ul") 两次。但是,如果您希望 $(".testimonialsCntnr ul").children() 发生变化,那么您将需要使用我的第一个示例。

【讨论】:

  • 这是不必要的低效。 OP 现在必须调用 testimonialsBelt.childrenElem() 才能拉出属性,而后者又必须调用 parentElement.children()。这只有在 UL 在脚本的整个生命周期内动态添加列表项时才可接受。
  • 这是非常错误的。 UL 很可能是动态的。
  • 您如何确定 UL 在页面加载后“极有可能”改变大小? OP 的代码 sn-p 写得好像 children().length 实际上不会改变。
  • 只有一小部分代码可见。如果没有 OP 的意图解释,您的假设是非法的。
  • 也许,但可用代码肯定不支持 UL 在运行时更改的“高概率”。
【解决方案2】:

在 JavaScript(不是 ECMAScript)中,你可以使用这个:

testimonialsBelt={
        parentElment:#1=$(".testimonialsCntnr ul"),
        childrenElem:#1#.children().length
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    相关资源
    最近更新 更多