.x"), y: $("someSelector > .y"), -6ren">
gpt4 book ai didi

javascript - 如何将方法应用于整个对象文字?

转载 作者:行者123 更新时间:2023-11-28 15:42:50 26 4
gpt4 key购买 nike

如何将方法应用于对象文字的所有属性?

例如:

var ObjL = {
x: $("someSelector > .x"),
y: $("someSelector > .y"),
otherx: $("someOtherSelector > .x"),
othery: $("someOtherSelector > .y"),
...
...
...
}
// <---something like ObjL.css("background-color","red") would go here

您会使用ObjL.someMethod()吗?

你能用数组来做这个吗?

最佳答案

如果我理解正确的话,您想将 method aMethod 应用于元素?恕我直言,最好的解决方案是 foreach 循环:

$.each($obj, function(prop, value) {
//call a method here, being the same on value or this.
value.css(blablabla, blablabla);
});

(我故意没有使用for循环,因为1.你使用的是jquery并且它更短,2.它在拥有或继承的proto属性方面有很多问题)。

编辑:是的,您也可以对数组使用 $.each 循环。另一种方法是使用常规的 for-counter 循环 (for(initial;condition;increment){ code }),因为在数组中使用 for(in) 循环会导致意外结果。

关于javascript - 如何将方法应用于整个对象文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23277750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com