在可排序的JQuery中动态地将索引值分配给列表元素值 [英] Assign a index value to the list element value dynamically in sortable JQuery

查看:72
本文介绍了在可排序的JQuery中动态地将索引值分配给列表元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有一个可排序的列表,在这里我需要将每个列表元素的值设置为其索引值.前任.如果元素ex1变成第二个,那么我需要为其设置一个值1(从0开始计数),如果元素ex2变成第三个,那么值为2,依此类推.我试图通过在sortable的update方法中设置值来实现这一点.但是,每当我尝试运行时,它都不会更新值状态,它会堆积在默认的初始值上.

I need to have sortable list where I need to set the value of every list element to its index value, for. ex. if element ex1 becomes second then I need to set a value for it of 1 (counting from 0), if element ex2 becomes third then value of 2, and so on. I'm trying to achieve that by setting value inside the update method of sortable. But every time I'm trying to do run that it is not updating the value state, it stacks on default initial value.

这里是Js小提琴,您可以检查它(只需更改列表上的顺序并检查devtools中的值,看看它保持不变).

Here's Js fiddle you can check it (just change the order on the list and check values inside devtools, look how it stays the same).

const orderedList = $('li');

$('ul').sortable({
  update: function() {
    orderedList.each(function(idx) {
      $(this).attr("value", idx);
    })
  }
});

https://jsfiddle.net/xpvt214o/896382/

推荐答案

您可以只更新函数,基本上是在全局定义const值,因此不会更新值.在修改集合时.

you can just update your function, basically you are defining a const value globally,so value is not updated. when you are modifying a collection.

$('li').each(function(idx){
  $(this).attr("value", idx);
})

const getValue = $('li:first-child').attr("value");
$('h4').text(getValue);

$('ul').sortable({
  update: function() {
    var _li= $('li');
    _li.removeAttr("value");
    _li.each(function(idx) {
      var currentObj=$(this);
      console.log(currentObj.text());
      $(this).attr("value", idx);
    })
  }
});

此处

这篇关于在可排序的JQuery中动态地将索引值分配给列表元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆