使用 JQuery 对具有唯一 rel 属性的元素执行功能
我试图通过自动检测填充一组链接的“rel”属性的值来提高一些代码的可移植性,以便我可以在页面上创建多个图像灯箱。基本上,现在我正在从数据库中提取有关酒店的数据,对于我发现的每家酒店,我正在创建一个由 JCarousel 组成的简单图像库,并且对于每个 JCarousel,可以单击图像来启动仅包含图像的灯箱从那组。这是我目前用来实现我的目标的代码:
$(document).ready(function(){
$(".carousel").jcarousel({
wrap: 'circular',
visible: 3,
scroll: 1
});
$('a.lightbox[rel=9]').lightBox();
$('a.lightbox[rel=10]').lightBox();
$('a.lightbox[rel=11]').lightBox();
$('a.lightbox[rel=13]').lightBox();
});
当前方法的问题是,如果其他人将酒店添加到数据库中(情况总是如此),图像将出现在轮播中,但不会出现有灯箱效果,除非我手动添加它。如果我计划在多个网站上使用此代码(我确实这么做了),这意味着相当大量的维护工作。
我希望能够做的是检测 a.lightbox 元素的独特“rel”属性,并在 $.each 中循环它们以应用灯箱效果。我只是不知道该怎么做。有什么建议吗?
I am attempting to improve the portability of a bit of code by automatically detecting what values populate the "rel" attribute of a set of links so that I can create multiple image lightboxes on a page. Basically, right now I am pulling data about hotels from a database, and for each hotel I find I am creating a simple image gallery that consists of a JCarousel, and for each JCarousel the images are able to be clicked launching a lightbox containing only images from that set. Here is the code I currently use to accomplish my goal right now:
$(document).ready(function(){
$(".carousel").jcarousel({
wrap: 'circular',
visible: 3,
scroll: 1
});
$('a.lightbox[rel=9]').lightBox();
$('a.lightbox[rel=10]').lightBox();
$('a.lightbox[rel=11]').lightBox();
$('a.lightbox[rel=13]').lightBox();
});
The problem with the current approach is that if someone else adds a hotel to the database (which will always be the case) the images will appear within the carousel, but will not have the lightbox effect unless I manually add it. This means a fairly significant amount of upkeep if I plan on using this code across multiple websites (which I do).
What I would like to be able to do is detect the unique "rel" attributes for a.lightbox elements, and loop through them in a $.each to apply the lightbox effect. I'm just not sure how to do that. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
Object
作为一种关联数组来存储看到的rel
属性:然后您可以依次将灯箱应用到每个唯一的
rel
值:注意:
Object.keys
是一个 ES5 函数。有关兼容性功能,请参阅 Mozilla 开发者网络 站点。Use an
Object
as a kind of associative array to store the seenrel
attributes:Then you can apply your lightbox to each unique
rel
value in turn:NB:
Object.keys
is an ES5 function. See the Mozilla Developer Network site for a compatibility function.你可以试试这个
You can try this