javascript - 在子元素内移动多个元素

标签 javascript jquery html css

我为 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);
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/95wtuuw9/

关于javascript - 在子元素内移动多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26363691/

相关文章:

javascript - Ajax/jQuery post 之后从 DOM 获取值

php - 如何让我的聊天分区显示在彼此下方

html - CreateJs Canvas 形状在 Windows Phone 上丢失坐标

javascript - 如何构建 Angular2 应用程序?

javascript - 选择页面后更改 anchor 标记的 CSS - 单页网站

javascript - 清除 Firebug 中所有断点的键盘快捷键

jquery - jQuery 中的 HTML 表格排序

javascript - Rails 没有处理我的 jQuery .click 事件(甚至无法弹出警报。)

javascript - 使用 FormKeep,如何将请求的 Accept header 设置为 application/javascript

javascript - Knockoutjs - 在使用 foreach 而不是选项时丢失了选择值的两种绑定(bind)方式