我为 8 个不同的菜单项重复了以下代码:
<li>
<a> <img class="menu-img" src="bg.jpg"></a>
<div class="sub-container">
<div class="sub-menu"></div>
</div>
</li>
现在我想将 img 向下移动到子容器中,我已经使用以下代码实现了这一点:
$("img.menu-img") //element i'm targetting
.appendTo(".sub-container"); // where I'm moving it to
但正如您所猜到的,每次我将另一个图像添加到不同的菜单时,它都会将其添加到此容器中。我该怎么做才能让它只将图像向下移动到该元素的子元素中,这样每个菜单都会有一个独特的图像?
谢谢。
最佳答案
您可以迭代所有匹配项,然后导航一个分支以找到每个 img 的目标:
$("img.menu-img").each(function(){
// Find the closest parent LI element
var li = $(this).closest('li');
// Find the container within that LI and move the image (this) under there
li.find(".sub-container").append(this);
});
关于javascript - 在子元素内移动多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26363691/