董哥给的demo
其他自己的实现;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
.box{
background:#ccc;
width:200px;
height:200px;
display:inline-block;
position:relative;
}
.box span{
float:left;
padding:3px 10px;
background:#555;
color:#fff;
margin:5px;
font-size:12px;
cursor:pointer;
}
.box .btn{
position:absolute;
bottom:0;
width:100%;
background:#999;
text-align:center;
}
</style>
<body>
<div class="box" id="box1">
<div class="cont"></div>
<div class="btn">
<button>清空</button>
<button>排序</button>
</div>
</div>
<div class="box" id="box2">
<div class="cont"></div>
<div class="btn">
<button>清空</button>
<button>排序</button>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function(){
//数据源
var Data = {
d1:['9','5','4','3','2'],
d2:['7','8','1']
};
//分配数据
var loadItem = function(data){
var html = '';
for(var i = 0, len = data.length; i < len; i++){
html = html + '<span>'+ data[i]+'</span>'
}
return html;
};
var reload = function (){
$('#box1 .cont').html(loadItem(Data.d1));
$('#box2 .cont').html(loadItem(Data.d2));
};
//首次加载
reload();
//jquery事件绑定
$('.box').on('click', function(e){
var cell = e.target; //当前点击的对象
var txt = cell.innerText; //当前对象的值
//点击单元格
if(cell.tagName === 'SPAN'){
//判断单元格父级容器用来确定使用那个数据源
//indexOf可以返回字符串首先出现的位置
if(this.id === 'box1'){
Data.d1.splice(Data.d1.indexOf(txt), 1);
Data.d2.push(txt);
}else{
Data.d2.splice(Data.d2.indexOf(txt), 1);
Data.d1.push(txt);
}
//每次点击重新加载
console.log(Data.d1,Data.d2);
reload();
}
//点击清空按钮
if(cell.tagName === 'BUTTON' && cell.innerText === '清空'){
if(this.id=='box1'){
var num = $("#box1 .cont").children();
$("#box1 .cont").empty;
$("#box2 .cont").append(num);
}else{
var num = $("#box2 .cont").children();
$("#box2 .cont").empty;
$("#box1 .cont").append(num);
}
}
//点击排序按钮
if(cell.tagName === 'BUTTON' && cell.innerText === '排序'){
var nwords = [];
var words = [];
var cmd = [] ;
if(this.id=='box1'){
var words = $("#box1 .cont").children();
for(var i = 0;i<words.length;i++){
nwords[i] = words[i].innerHTML;//获取span中的内容 只能用innerHTML来获取
}
nwords.sort();
$("#box1 .cont").empty();
$("#box1 .cont").html(loadItem(nwords));
}else{
var words = $("#box2 .cont").children();
for(var i = 0;i<words.length;i++){
nwords[i] = words[i].innerHTML;//获取span中的内容 只能用innerHTML来获取
}
nwords.sort();
$("#box2 .cont").empty();
$("#box2 .cont").html(loadItem(nwords));
}
}
})
});
</script>
</body>
</html>