我在 div 中有一組跨度,我試圖匹配并移動到相應的 id。每個跨度都有一個與目標的父 ID 匹配的資料屬性。我正在嘗試使用 jQuery 來匹配跨度中的資料屬性,然后將它們附加到父 div ID 中的單獨跨度之前。
這是我的代碼:
HTML
<div id="id-expand-2">
<a class="thing" href="#">
<div class="item-title">
<span>Title 1</span>
</div>
</a>
</div>
<div id="id-expand-4">
<a class="thing" href="#">
<div class="item-title">
<span>Title 2</span>
</div>
</a>
</div>
<div id="id-expand-6">
<a class="thing" href="#">
<div class="item-title">
<span>Title 3</span>
</div>
</a>
</div>
<div class="vid-imgs">
<span class="item" data-item="id-expand-2"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span class="item" data-item="id-expand-4"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span class="item" data-item="id-expand-6"><img src="https://www.fillmurray.com/g/140/100" /></span>
</div>
基本上,每一個是在跨度vid-imgs與類data-item將匹配到母體的div的ID,然后做一個.append()后右item-title類。
所以預期的輸出將是這樣的:
<div id="id-expand-2">
<a class="thing" href="#">
<div class="item-title">
<span class="item" data-item="id-expand-2"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span>Title 1</span>
</div>
</a>
</div>
<div id="id-expand-4">
<a class="thing" href="#">
<div class="item-title">
<span class="item" data-item="id-expand-4"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span>Title 2</span>
</div>
</a>
</div>
<div id="id-expand-6">
<a class="thing" href="#">
<div class="item-title">
<span class="item" data-item="id-expand-6"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span>Title 3</span>
</div>
</a>
</div>
我不知道如何匹配這些整體。
我正在考慮像這樣使用每個:
$(".vid-imgs").each(function () {
var items = $(".item").attr("data-item");
console.log(items);
});
但這似乎只抓取了vid-imgsdiv 中的第一項。我覺得我以前做過這件事,但我一整天都在做這件事,我想我需要讓我的眼睛休息一下。
uj5u.com熱心網友回復:
幾樣東西:
$(".item").attr("data-item");正在獲取 的data-item屬性值.item。如果要選擇具有特定的專案id,可以使用CSS id 選擇器你應該回圈遍歷
span里面的s.vid-imgs,而不是.vid-imgs它本身
$(".vid-imgs span").each(function () {
var items = $("div#" $(this).data('item'))
items.append(this.cloneNode(true))
this.remove() //remove the span
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id-expand-2">
<a class="thing" href="#">
<div class="item-title">
<span>Title 1</span>
</div>
</a>
</div>
<div id="id-expand-4">
<a class="thing" href="#">
<div class="item-title">
<span>Title 2</span>
</div>
</a>
</div>
<div id="id-expand-6">
<a class="thing" href="#">
<div class="item-title">
<span>Title 3</span>
</div>
</a>
</div>
<div class="vid-imgs">
<span class="item" data-item="id-expand-2"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span class="item" data-item="id-expand-4"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span class="item" data-item="id-expand-6"><img src="https://www.fillmurray.com/g/140/100" /></span>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326169.html
標籤:javascript html 查询 css
上一篇:模式匹配或地圖單體
