html代码块:
脚本以及数据:
dataNodes: [{ name: '', class: '', reports: 0 }]
操作事件方法:
// 添加文本域
addNode() {
this.dataNodes.push({ name: '', class: '', reports: 0 })
},
// 移动文本域位置
changeSort(index, type) { // index为所操作对象的下标、type为是升序(0:升序),还是降序(1:降序)
if (index === 0 && type === 0) {
this.$message.warning('已是第一列元素!') // 判断是否为第一位元素 并禁止升序
} else if (index === this.dataNodes.length - 1 && type === 1) {
this.$message.warning('已是最末尾元素!') // 判断是否为末位元素(通过数组对象的长度 -1为具体个数 不理解的请自行不可js中.length的用法) 并禁止降序
} else { // 通过使用splice()函数对数据进行操作
this.dataNodes.splice(
type ? index : index - 1, 1,
...this.dataNodes.splice(type ? index + 1 : index, 1, this.dataNodes[type ? index : index - 1])
)
}
},
// 删除文本域
delNoed(dataNode) {
var index = this.dataNodes.indexOf(dataNode) // 定义当前被操作具体对象
if (this.dataNodes.length > 1) { // 因为我在此文本域需要至少保留一项 所以加此判断 如不需要 移除if判断即可
this.dataNodes.splice(index, 1) // 使用splice() 函数进行删除操作 index:当前被操作的具体对象,1:为删除的数量(即当前)
} else {
this.$message.warning('至少保留一项!')
}
}
操作图:
禁止升序:
禁止降序:
将王二往上升序:
将小李子往下降序:
删除以及验证:
代码部分的具体功能含义都加上了注释 另附上相关.length和splice()函数的链接 当前项目代码是使用的vue以及element-ui 如果需求是jQuery或 js 将数据dataNodes定义为全局变量,然后方法直接使用就可
脚本代码:
<script>
var dataNodes = [{ name: '', class: '', reports: 0 }];
// 添加文本域
function addNode() {
dataNodes.push({ name: '', class: '', reports: 0 });
};
// 移动文本域位置
function changeSort(index, type) { // index为所操作对象的下标、type为是升序(0:升序),还是降序(1:降序)
if (index === 0 && type === 0) {
this.$message.warning('已是第一列元素!') // 判断是否为第一位元素 并禁止升序
} else if (index === dataNodes.length - 1 && type === 1) {
this.$message.warning('已是最末尾元素!') // 判断是否为末位元素(通过数组对象的长度 -1为具体个数 不理解的请自行不可js中.length的用法) 并禁止降序
} else { // 通过使用splice()函数对数据进行操作
dataNodes.splice(
type ? index : index - 1, 1,
...dataNodes.splice(type ? index + 1 : index, 1, dataNodes[type ? index : index - 1])
)
}
};
// 删除文本域
function delNoed(dataNode) {
var index = dataNodes.indexOf(dataNode) // 定义当前被操作具体对象
if (dataNodes.length > 1) { // 因为我在此文本域需要至少保留一项 所以加此判断 如不需要 移除if判断即可
dataNodes.splice(index, 1) // 使用splice() 函数进行删除操作 index:当前被操作的具体对象,1:为删除的数量(即当前)
} else {
this.$message.warning('至少保留一项!')
}
}
</script>
.length:https://www.w3school.com.cn/jsref/jsref_length_array.asp
splice()函数:https://www.w3school.com.cn/jsref/jsref_splice.asp
源码链接:https://download.youkuaiyun.com/download/qq_41193701/12077167