[英]Jquery - Multiple elements with the same class but different IDs to use the same function by with different results
I am working on a music site that would like the the album covers as links to the track listings for that particular release. 我正在一个音乐网站上工作,希望专辑封面可以作为该特定发行版曲目列表的链接。
My issue with having an image link would mean I would not be able to put any sort of descriptive text accompanying the image, unless it was an overlay, a tooltip or it to appear just below or somewhere around the image. 我遇到的具有图像链接的问题意味着,除非图像是叠加层,工具提示或它出现在图像的下方或周围,否则我将无法在图像的后面放置任何类型的描述性文本。
It is very possible to achieve a similar effect I am trying to achieve with PHP (the site would be running on WP), but that may be an issue with download speeds, screen sizes. 我尝试使用PHP可以达到类似的效果(该站点将在WP上运行),但是这可能与下载速度,屏幕尺寸有关。
So I am wondering if such an effect can be achieved using JQuery. 所以我想知道是否可以使用JQuery达到这种效果。
Here is a basic structure of what I am looking to do. 这是我要做什么的基本结构。
This would be how the HTML looks for each release link: 这就是每个发布链接的HTML外观:
<div class="box cover" id="uni-123">
<a href="hover" id="page-title">This is the text</a>
</div>
<div class="box cover" id="uni-124">
<a href="hover" id="page-title-2">This is the text</a>
</div>
Style would get the sizing correct for the imagery... 样式将使图像的尺寸正确无误。
.box {width: 200px; height: 200px; border: 1px solid black;}
.box a {display: block; width: 200px; height: 200px; color: white;}
And then the JQuery would use the unique id's of each box to determine which imagery to get... 然后,jQuery将使用每个框的唯一ID来确定要获取的图像...
function boxImage(){
var boxId = $('.box').attr("id");
var image = $('#' + boxId + ' > a ').attr("id");
$('#' + boxId).css({"background":"url(" + image + ".jpg)","background-size":"contain"});
}
$(document).ready(boxImage);
Obviously the trouble I am having is that the imagery only shows up on the first instance of .box, not all of them... SO is there a way for the boxImage function to take effect on all instances rather than on just the first... and if so... HOW? 显然,我遇到的麻烦是图像仅显示在.box的第一个实例上,而不是全部显示在其中。因此,boxImage函数有一种方法可以在所有实例上而不是仅在第一个实例上生效。 ..如果是的话。
Thanks in advanced, Matt 谢谢你,马特
try this: 尝试这个:
$(function() {
$('.box').each(function() {
var boxId = $(this).attr("id");
var image = $('#' + boxId + ' > a ').attr("id");
$('#' + boxId).css({"background":"url(" + image + ".jpg)","background-size":"contain"});
});
});
So your problem is you are applying your function call only once when page loads. 因此,您的问题是页面加载时仅应用一次函数调用。 You need to loop through all
.box
elements to apply same effect to all. 您需要遍历所有
.box
元素才能对所有.box
应用相同的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.