通过数组 对表单文本域的动态新增、排序(数据上、下移动)、删除

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.csdn.net/download/qq_41193701/12077167

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值