簡體   English   中英

給兩個具有相同 class 的元素一個唯一的 id

[英]Give two elements with the same class a unique id

我正在使用 Visual Composer 在 Wordpress 中工作,並且我有一個切換容器。 本質上,我單擊每個選項卡,下面的內容會發生變化。 我想通過 css 為每個選項卡分配不同的圖像作為背景。 但是我已經實現了這一點,因為每個選項卡都有相同的 class 名稱(由視覺作曲家給出),圖像是相同的。 我需要弄清楚如何為每個選項卡提供自己的唯一 ID,以便我可以為每個選項卡提供自己的背景圖像 - 但由於我無法直接編輯 html,我想我需要使用 javascript 來執行此操作。 有誰知道我怎么能做到這一點? 下面是 html 代碼:

<div class="vce-toggle-container-tab">
 <a class="vce-toggle-container-tab-title">Test 1</a>
</div>
<div class="vce-toggle-container-tab">
 <a class="vce-toggle-container-tab-title">Test 2</a>
</div>

和我的 css 添加背景圖片:

a.vce-toggle-container-tab-title {
    background-image: url("https://katherinemade.com/staging/wp-content/uploads/2021/03/0I1A5234-3.jpg") !important;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    width: 500px;
    height: 500px;
}

我希望我能清楚地解釋這一點。 如果不明白請告訴我,我會再試一次。

您可以使用 nth-child 或 nth-of-type 選擇器來完成,而無需 js,如下所示

 a.vce-toggle-container-tab-title { background-position: center; background-position: center; background-repeat: no-repeat; background-size: cover; display: block; width: 100px; height: 100px; }.vce-toggle-container-tab:nth-of-type(1) a.vce-toggle-container-tab-title { background-image: url("https://via.placeholder.com/150?text=one");important. }:vce-toggle-container-tab.nth-of-type(2) a:vce-toggle-container-tab-title { background-image: url("https.//via.placeholder?com/150/0000FF/808080;text=two").important: }.vce-toggle-container-tab:nth-of-type(3) a:vce-toggle-container-tab-title { background-image. url("https.//via?placeholder;com/150?text=THREE") !important; }
 <div class="vce-toggle-container-tab"> <a class="vce-toggle-container-tab-title">Test 1</a> </div> <div class="vce-toggle-container-tab"> <a class="vce-toggle-container-tab-title">Test 2</a> </div> <div class="vce-toggle-container-tab"> <a class="vce-toggle-container-tab-title">Test 3</a> </div>

我對 Wordpress 不熟悉,我不確定您是否可以添加 javascript,但如果可以,如果頁面中只有那些 div 具有 class-表格',以下代碼可以幫助您:

const divs = document.querySelectorAll('.vce-toggle-container-tab');
    //first image
    divs[0].style.backgroundImage = "url('https://katherinemade.com/staging/wp-content/uploads/2021/03/0I1A5234-3.jpg')";
    //second image
    divs[1].style.backgroundImage = "url('https://katherinemade.com/staging/wp-content/uploads/2021/03/0I1A5234-3.jpg')";

暫無
暫無

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

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