1

I'm trying to figure out how to reorder a ul using a textbox value.

Start with a ul....

<ul id="ItemList">
    <li> <some text>  <input id="Text1" type="text" value="1" /></li>
    <li> <some text>  <input id="Text2" type="text" value="2" /></li>
    <li> <some text>  <input id="Text3" type="text" value="3" /></li>
    <li> <some text>  <input id="Text4" type="text" value="4" /></li>
</ul>

Then if I change the value of Text4 from 4 to 2 the list will reorder itself while changing the value of text2 & 3 to 3 & 4 respectively.

I suspect I'm not the first person to have to do this, so if there's pointers available.

I'm not finding anything specific here, but I may not be searching right.

4

1 回答 1

1

这是一个快速的方法(没有错误检查):

$('input').keyup(function () {
    var start = $(this).index('input');
    var target = $(this).val() - 1;
    if (target < start) $(this).parent().insertBefore($('li').eq($(this).val() - 1));
    if (target > start) $(this).parent().insertAfter($('li').eq($(this).val() - 1));
});

jsFiddle 示例

请注意,如果您想在更改后重新编号输入,请将此行添加到函数的末尾$('input').each(function(){$(this).val($(this).index('input')+1)});

于 2013-07-19T18:48:21.917 回答