【问题标题】:jQuery swap multiple elementsjQuery交换多个元素
【发布时间】:2014-05-03 22:27:28
【问题描述】:

我有一个 div 和一个链接的三个组 (td),我想将链接放在每个组 (td) 中的 div 之前。我尝试使用 after() 但没有成功.. 有没有简单的方法可以做到这一点?

我有这个结构:

<table>
    <tr>
        <td>
            <div>Text</div>
            <a href="#">Link</a>
        </td>
        <td>
            <div>Text</div>
            <a href="#">Link</a>
        </td>
        <td>
            <div>Text</div>
            <a href="#">Link</a>
        </td>
    </tr>
</table>

【问题讨论】:

  • 你用.after()写的代码是什么?它有什么问题?
  • 感谢您的评论,我得到了它与 Josh 的代码一起使用..

标签: jquery html css swap


【解决方案1】:

如果您希望 a 元素成为第一个子元素,请使用以下内容:

Example Here

$('table td a').each(function(){
    $(this).prependTo($(this).parent());
});

或者,如果您只想将其插入到其前一个兄弟之前,您也可以使用它。

Example Here

$('table td a').each(function(){
    $(this).insertBefore($(this).prev());
});

【讨论】:

    【解决方案2】:

    非 jQuery 替代方案:

    [].slice.call(document.querySelectorAll('td')).forEach(function(td) {
        td.insertBefore(td.children[1], td.children[0]);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      相关资源
      最近更新 更多