使用jQuery将匹配data属性的元素插入对应ID容器的指定位置
问题原因
你之前的代码存在两个问题:
- 遍历的对象是
.vid-imgs容器本身,而不是容器内的多个.item元素,所以只会执行一次遍历逻辑 - 直接调用
$(".item").attr("data-item")时,jQuery的attr方法在匹配多个元素时只会返回第一个元素的对应属性,因此只能拿到第一个span的data-item值。
实现代码
你可以直接遍历所有.vid-imgs下的.item元素,逐个匹配目标容器后移动即可:
$(".vid-imgs .item").each(function () { // 缓存当前处理的span元素 const $cur = $(this); // 获取对应目标容器的ID const targetId = $cur.data('item'); // 定位到目标容器内的标题span,将当前元素插入到它前方 $cur.insertBefore(`#${targetId} .item-title > span:first`); });
如果需要增加健壮性,避免目标容器不存在时报错,可以加一层存在性判断:
$(".vid-imgs .item").each(function () { const $cur = $(this); const targetId = $cur.data('item'); const $target = $(`#${targetId} .item-title > span:first`); if ($target.length) { $cur.insertBefore($target); } });
逻辑说明
- jQuery的
insertBefore方法会直接将元素从原有位置移动到目标位置,不需要额外删除原位置的元素 - 使用
data('item')读取自定义data属性是jQuery推荐的写法,比直接调用attr('data-item')更规范 - 选择器
span:first是为了确保只匹配.item-title下的第一个标题span,避免容器内有其他span时逻辑出错
内容的提问来源于stack exchange,提问作者ultraloveninja
相关产品推荐
相关产品推荐

