我有四张足球运动员 table ,一张用于守门员,一张用于后卫,一张用于中场球员,一张用于进攻球员。我希望用户能够更改玩家的位置,以便他从当前的表格中消失并出现在另一个表格中,而无需刷新页面。
我能想到的唯一方法是让每个玩家都列在所有四个表中,但对其中三个表隐藏他。然后,如果他发生变化,我会将他隐藏在当前表格中,并在另一个表格中显示他。
我知道如何实现这一点,但似乎有点沉重,我想知道是否有更优雅的解决方案。
最佳答案
您可以在纯 JavaScript 中使用 appendChild()
将节点从一个位置移动到另一个位置。该节点会自动从 DOM 中的旧位置删除。
引用 Mozilla 开发者网络 documentation on appendChild
:
If the given child is a reference to an existing node in the document,
appendChild()
moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, it is first removed, then appended at the new position.
以下代码片段演示了如何使用 appendChild()
在表之间移动行。单击移动
按钮可将项目从一个表移动到另一个表。
window.onload = function () {
var data = {
like: ['vanilla', 'pistachio', 'squirrels', 'squash', 'mountains'],
dislike: ['chocolate', 'trucks', 'football', 'hard candy', 'valleys']
};
var tables = {};
var moveMe = function () {
this.table = tables[this.table === tables.like ? 'dislike' : 'like'];
this.table.tbody.appendChild(this.tr);
};
Object.keys(data).forEach(function (key) {
var container = document.createElement('div'),
table = tables[key] = document.createElement('table'),
tbody = table.tbody = document.createElement('tbody');
data[key].forEach(function (item) {
var tr = document.createElement('tr'),
td = document.createElement('td');
td.innerHTML = item;
tr.appendChild(td);
tbody.appendChild(tr);
var button = document.createElement('button');
button.innerHTML = 'move';
button.onclick = moveMe;
button.table = table;
button.tr = tr;
td.appendChild(button);
});
table.appendChild(tbody);
var header = document.createElement('h2');
header.innerHTML = key;
container.appendChild(header);
container.appendChild(table);
container.className = 'container';
document.getElementById('wrapper').appendChild(container);
});
};
* {
box-model: border-box;
}
body {
font-family: sans-serif;
}
#wrapper {
width: 450px;
}
.container {
display: inline-block;
width: 200px;
padding: 10px;
}
h2 {
margin: 5px 0;
color: #666;
}
table {
width: 200px;
border-collapse: collapse;
}
td {
color: #333;
padding: 10px;
border: 1px solid #bbb;
position: relative;
}
td button {
position: absolute;
right: 5px;
top: 5px;
border: 2px solid #ccc;
border-radius: 5px;
background: #fff;
font-size: 12px;
}
td button:hover {
outline: none;
border-color: #888;
cursor: pointer;
}
<div id="wrapper"></div>
关于javascript - 使用 JavaScript 或 jQuery 在表之间移动项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703177/