jQuery - 按容器选择一组元素并将其分组
我需要根据
或
容器选择一组图像链接并将其分组。例如,在此 HTML 中:选择前两个链接,在其上附加我的函数,选择接下来的两个链接,运行函数...等等
DIV
LINK
LINK
DIV
LINK
LINK
UL
LINK
LINK
/UL
/DIV
UL
LINK
LINK
/UL
/DIV
LINK
LINK
...
(每个 div/ul 可以有任意数量的链接)
现在我有this:
$('div').each(function(index){
var elements = $(this).find('a').filter(function(){
return !!this.href.match('(\.jpg|\.jpeg|\.png|\.gif)$');
});
console.log('------' + index + '------');
console.log(elements);
});
将链接过滤为仅图像链接。 但它并没有真正像我想要的那样对它们进行分组,并且我的函数在同一元素上运行多次......
有什么建议吗?
I need to select and group a set of image links based on their <DIV>
or <UL>
container.
For example, in this HTML: select the first two links, attach my function on them, select the next two links, run the function ... and so on
DIV
LINK
LINK
DIV
LINK
LINK
UL
LINK
LINK
/UL
/DIV
UL
LINK
LINK
/UL
/DIV
LINK
LINK
...
(each div/ul can have any number of links)
Right now I have this:
$('div').each(function(index){
var elements = $(this).find('a').filter(function(){
return !!this.href.match('(\.jpg|\.jpeg|\.png|\.gif)
which filters down the links to only to ones that are images.
but it doesn't really group them like I want and my function runs more than once on the same element...
Any suggestions?
);
});
console.log('------' + index + '------');
console.log(elements);
});
which filters down the links to only to ones that are images.
but it doesn't really group them like I want and my function runs more than once on the same element...
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为您可能在 DIV/UL 和 A 之间有元素,例如 LI,所以您可以首先选择 A 并将它们“分组”:
Because you probably have elements between the DIV's/UL's and the A, such as LI, you can start by selecting the A's and "group" them:
如果您只需要将事物组合在一起,也许这样的东西适合您。
使用您的标记:
将生成以下内容:
If you just need to group things together maybe something like this will work for you.
With your markup:
Will produce the following:
不能将选择器与子属性一起使用吗?
即:
上面将选择所有 div 和 ul(可能想要在此处应用特定样式或某些内容以仅选择您想要的样式),然后它会获取子 a 元素。
Can you not use the selector with a child property?
ie:
The above will select all divs and uls (might want to apply a specific style or something here to only select the ones you want) then it gets the child a elements.
我认为这就是您想要的,但我不确定您到底想对元素做什么:
I think this is what you want but I'm not sure exactly what you want to do to the elements: