单击时移动按钮



单击按钮时,如何将button从id为two的div移动到id为one的div?

<div id="one">
</div>
<div id="two">
<button onclick="moveMe"></button>
</div>
function moveMe() {
// ??
}

我们可以使用removeChildappendChildjs功能来实现这一点。下面提供了一个带有工作代码的示例。

const one =  document.getElementById("one");
const two =  document.getElementById("two");

const allButtons = document.getElementsByTagName("button");
for(let i = 0; i < allButtons.length; i++) {
const btn = allButtons[i];
btn.addEventListener("click", function(e) {
const el = e.currentTarget;
const newParent =  el.parentNode.id == "one" ? two : one;
el.parentNode.removeChild(el);
newParent.appendChild(el)
});
}
.section {
height: 100px;
width: 150px;
padding: 4px;
margin: 5px;
float: left;
}
#one {
background: #CCC;
}
#two {
background: #eee;
}
button {
margin: 2px;
padding: 4px;
}
<h3>Toggle button between container on click</h3>
<div>
<div class="section" id="one"></div>
<div class="section" id="two"> <button>Move me 1</button> <button>Move me 2</button></div>
</div>

function moveMe() {
const divTwo = document.getElementById("two")
const divOne = document.getElementById("one")

const newButton = document.createElement("button")
newButton.innerText = "Click me"

divOne.appendChild(newButton)
divTwo.children[1].remove()
}
<div id="one">
<p>
div one
</p>
</div>
<div id="two">
<p>
div two
</p>
<button onclick="moveMe()">Click me</button>
</div>

你可以试试这个:

// select the elements
const button = document.querySelector('button');
const firstDiv = document.getElementById('one');
// add eventListener
button.addEventListener('click', moveButton);
// move the button
function moveButton() {
firstDiv.append(button);
}
<div id="one">
</div>
<div id="two">
<button id="btn" onclick="moveMe">MoveMe</button>
</div>
function moveMe() {
var divOne = document.querySelector("#one");
var btn = document.querySelector("#btn");
divOne.appendChild(btn);
}

您可以使用下面的代码来移动元素。

,我对你的代码做了一些更改

您可以使用版本1或版本2

  • 第一个版本的变化是我添加了";id";属性,这样我们就不会只将标记用作选择器,当然您也可以使用#two>按钮使其更精确
  • 第二个版本的变化是我给你的函数添加了一个参数,这次它将使用"处理当前元素;这个";调用函数时的关键字

function moveMe(){
// one.appendChild(document.querySelector("button"));
one.appendChild(move);
}
function moveMeV2(element){
one.appendChild(element);
}
<div id="one">
<span>one</span>
</div>
<div id="two">
<span>two</span>
<button id="move" onclick="moveMe()">Move Me</button>
<button onclick="moveMeV2(this)">Move Me V2</button>
</div>

最新更新