如何在JavaScript中交换HTML元素? [英] How to swap HTML elements in javascript?

查看:190
本文介绍了如何在JavaScript中交换HTML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用经典的Javascript进行DOM脚本编写,我有一套DIV在容器DIV中。
对于小孩DIV的点击事件,我希望导致事件的孩子DIV与上面的DIV进行交换。
我的代码在这里..

I am using classic Javascript for DOM scripting, i have a set of DIV's in a container DIV. On click event of child DIV's, i want that the child DIV which has caused event to be swaped with the DIV above it.. my code goes here..

 <div id="container">
        <div onclick="swapDiv(event);">1</div>
        <div onclick="swapDiv(event);">2</div>
        <div onclick="swapDiv(event);">3</div>
 </div>

如果DIV 2被点击,它应该与DIV 1交换

if DIV 2 has been clicked it should be swap with DIV 1

推荐答案

此代码将执行您想要的(如果要使用第一个子元素交换所选的)。如果你想要别的东西,你需要更精确。

This code will do what you want (if you want to swap the selected with the first child element). In case you want something else you need to be more precise.

<script type="text/javascript">

function swapDiv(event,elem){
    elem.parentNode.insertBefore(elem,elem.parentNode.firstChild);
}

</script>


 <div id="container">
        <div onclick="swapDiv(event,this);">1</div>
        <div onclick="swapDiv(event,this);">2</div>
        <div onclick="swapDiv(event,this);">3</div>
 </div>

这篇关于如何在JavaScript中交换HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆