在开发中经常有上移、下移的操作,猛的一想感觉逻辑还很复杂,其实很简单主要有以下步骤:
- 首先页面上的展示列表在后台查询的时候要根据某个字段排序,这样展示的数据才是有序的,才可以实现此功能。
- 添加上移或者下移的时候需要把当前数据的ID和目标ID传到后台
- 后台排序的字段互换值,到前台后需要重新加载列表。
前台代码:
$.each(json,
function(index, item) {
// 循环获取数据
var answertext = '答案' + (index + 1) + '. ' + json[index].answertext;
var answerid = json[index].answerid;
var li = $("<li value=" + json[index] + ">" + answertext + "</li>");
li.appendTo("#ul_answer");
li.append(' <a onclick="deleteAnswer(\'' + answerid + '\')">删除</a>');
li.append(' <a onclick="updateAnswer(\'' + answerid + '\')">修改</a>');
var index = $("#ul_answer li").index(li);
var nextId = null;
var previousId = null;
if (index < (json.length - 1)) {
nextId = json[index + 1].answerid
}
if (index > 0) {
previousId = json[index - 1].answerid;
}
if (json.length > 1) {
if (index == 0) {
li.append('<a onclick="upordown(\'' + answerid + '\',\'' + nextId + '\')">下移</a>');
} else if (index == json.length - 1) {
li.append('<a onclick="upordown(\'' + answerid + '\',\'' + previousId + '\')">上移</a>');
} else {
li.append('<a onclick="upordown(\'' + answerid + '\',\'' + previousId + '\')">上移</a>');
li.append('<a onclick="upordown(\'' + answerid + '\',\'' + nextId + '\')">下移</a>');
}
}
});
$.ajax({
type: "GET",
url:'templateanswer/upordown',
data:{sourcePk:answerid,targetPk:targetId},
async: false,
contentType : 'application/json',
dataType:"json",
error: function(data) {
alert(data.message);
},
success: function(response) {
if(response.code='0000'){
// alert('删除成功');
init_answer();
}
}
});
后台代码:
Demo sourceDemo = this.getDemoyPk(sourcePk);
Demo targetDemo = this.getDemoByPk(targetPk);
Short sourceOrder = sourceDemo.getDemoorder();
Short targetOrder = targetOrder.getDemoorder();
sourceDemo.setQuestionorder(targetOrder);
targetOrder.setQuestionorder(sourceOrder);
this.questionDao.updateByPrimaryKey(sourceDemo);
this.questionDao.updateByPrimaryKey(targetDemo );