簡體   English   中英

jQuery-具有相同類但具有不同ID的多個元素通過不同的結果使用相同的功能

[英]Jquery - Multiple elements with the same class but different IDs to use the same function by with different results

我正在一個音樂網站上工作,希望專輯封面可以作為該特定發行版曲目列表的鏈接。

我遇到的具有圖像鏈接的問題意味着,除非圖像是疊加層,工具提示或它出現在圖像的下方或周圍,否則我將無法在圖像的后面放置任何類型的描述性文本。

我嘗試使用PHP可以達到類似的效果(該站點將在WP上運行),但是這可能與下載速度,屏幕尺寸有關。

所以我想知道是否可以使用JQuery達到這種效果。

這是我要做什么的基本結構。

這就是每個發布鏈接的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>

樣式將使圖像的尺寸正確無誤。

.box {width: 200px; height: 200px; border: 1px solid black;}
.box a {display: block; width: 200px; height: 200px; color: white;}

然后,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);

顯然,我遇到的麻煩是圖像僅顯示在.box的第一個實例上,而不是全部顯示在其中。因此,boxImage函數有一種方法可以在所有實例上而不是僅在第一個實例上生效。 ..如果是的話。

謝謝你,馬特

嘗試這個:

$(function() {
   $('.box').each(function() {
      var boxId = $(this).attr("id");
      var image = $('#' + boxId + ' > a ').attr("id");
      $('#' + boxId).css({"background":"url(" + image + ".jpg)","background-size":"contain"});
   });
});

因此,您的問題是頁面加載時僅應用一次函數調用。 您需要遍歷所有.box元素才能對所有.box應用相同的效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM