jQuery:如何使用设置对象键数量和键值本身的变量创建数组对象?
我正在努力解决这个问题,希望你能提供帮助。
我的目标是创建一个数组
的对象
,其中每个键
由一个变量
和设置此
是另一个键
的值数组
的过滤结果。
好吧,写起来很复杂,这是一个例子:
<!-- Markup -->
<section id="container">
<article class="class-1">1</article>
<article class="class-2">2</article>
<article class="class-3">3</article>
<article class="class-4">4</article>
<article class="class-5">5</article>
<article class="class-6">6</article>
<article class="class-7">7</article>
<article class="class-8">8</article>
<article class="class-9">9</article>
</section>
// Desired outcome:
// plugin variables are
{ columns:3 }
var cols = {
1 : [ $('.class-1') , $('.class-4') , $('.class-7') ],
2 : [ $('.class-2') , $('.class-5') , $('.class-8') ],
3 : [ $('.class-3') , $('.class-6') , $('.class-9') ]
};
// my jQuery so far:
// note : columns == 3
var cols = $.map( $('article','#container') , function(item, i) {
return {[ i%columns+1 : item ]};
});
我怎样才能实现我需要的东西? 我做错了什么?
任何帮助将不胜感激。
感谢您的阅读,
詹尼斯
I'm trying to wrap my head around this and was hoping you could help.
My goal is to create an object
of arrays
where each key
is set by a variable
and the values
of this key
are a filtered result of another array
.
Okay, that was complicated to write, here is an example:
<!-- Markup -->
<section id="container">
<article class="class-1">1</article>
<article class="class-2">2</article>
<article class="class-3">3</article>
<article class="class-4">4</article>
<article class="class-5">5</article>
<article class="class-6">6</article>
<article class="class-7">7</article>
<article class="class-8">8</article>
<article class="class-9">9</article>
</section>
// Desired outcome:
// plugin variables are
{ columns:3 }
var cols = {
1 : [ $('.class-1') , $('.class-4') , $('.class-7') ],
2 : [ $('.class-2') , $('.class-5') , $('.class-8') ],
3 : [ $('.class-3') , $('.class-6') , $('.class-9') ]
};
// my jQuery so far:
// note : columns == 3
var cols = $.map( $('article','#container') , function(item, i) {
return {[ i%columns+1 : item ]};
});
How can I achieve what I need here?
What am I doing wrong?
Any help would be much appreciated.
Thanks for reading,
Jannis
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想我明白你想做什么。您希望文章在加载时自动排序到列映射中,对吧?
我认为
.map
不会让你到达那里,因为它会返回一个数组。在您想要的输出中,您有一个带有每列键的对象。我认为你想要的是:I think I see what you're trying to do. You want the articles to automatically sort into a map of columns on load, right?
I don't think
.map
is going to get you there because it will return an array. In your desired output you have an object with keys for each column. I think what you want is something along the lines of:如何这样:
或者更动态的方法:
How about like this:
Or for a more dynamic approach: