javascript - jQuery UI onchange 每个循环未按预期工作

标签 javascript jquery html jquery-ui

我想要实现的是,当重新排列文本区域列表时,文本区域的名称更新为始终按升序排列。演示:

原创

name      content
value[0]  content0
value[1]  content1
value[2]  content2

重新排序(不一定按照这个顺序,只是一个例子)

name      content
value[0]  content2
value[1]  content0
value[2]  content1

我写的应该循环遍历列表并更新名称属性,但有时它不会,而其他时候它会使名称的顺序非常错误。这是我正在运行的 jQuery:

$(document).ready(function(){
    $( ".sortable" ).sortable();
    $( ".sortable" ).disableSelection();
    $( ".sortable" ).on("sortchange", function( event, ui ) {
        var $i = 0;
        $('.sortable > li').each(function(){
            $(this).children('textarea').attr( 'name', 'value[' + $i + ']' );
            $i++;
        });
    });
});

And a fiddle 。不确定我做错了什么。

最佳答案

使用sortstop而不是sortchange:

$(document).ready(function(){
    $( ".sortable" ).sortable();
    $( ".sortable" ).disableSelection();
    $( ".sortable" ).on("sortstop", function( event, ui ) {
        var $i = 0;
        $('.sortable > li').each(function(){
            $(this).children('textarea').attr( 'name', 'value[' + $i + ']' );
            $i++;
        });
    });
});

fiddle :https://jsfiddle.net/kz4t8ph5/2/

另请看看下面 Saif 的回答:)

关于javascript - jQuery UI onchange 每个循环未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236994/

相关文章:

php - PHP 如何在使用多个引号时进行 echo

html - 为什么 Chrome (v.51.0.2704.106 m) 会忽略“@meda all 和 (max-width :849)?

javascript - Vue.js : Call a Method from another Component

javascript - 使用 Javascript 隐藏和显示导航栏

javascript - 如何将三个js值传递给html中的标签?

javascript - 当我单击按钮时无法弄清楚如何在 js 中向下/向上滚动 50px

javascript - canvg 无法在 Edge 中工作

angularjs - 如何限制用户仅在 Angular 引导日期选择器中输入日期字段

c# - 使用多接口(interface)继承的 typescript 名称冲突/冲突

javascript - 如何在 Jquery-Steps 中刷新页面时保持同一向导?