JQuery – 如何将li移动到ul中的另一个位置? (交换2里)
什么是一种很酷的方式来应用它? 我需要一个在
- 中交换两个
- 位置的脚本。 它认为应该有可能实现。 感谢您的答复。
HTML
- Item 1
- Item 2
- Item 3
- Item 4
- Item 5
伪Javascript(JQuery)
$("#awesome ul li:eq(1)").exchangePostionWith("#awesome ul li:eq(3)");
HTML结果
- Item 1
- Item 4
- Item 3
- Item 2
- Item 5
您可以使用jQuery的
.after()
来移动元素。 我克隆了其中一个,所以原来可以保留为占位符。 就像你想要切换变量a
和b
,你需要第三个临时变量。$.fn.exchangePositionWith = function(selector) { var other = $(selector); this.after(other.clone()); other.after(this).remove(); };
现在你的伪代码
$("#awesome ul li:eq(1)").exchangePositionWith("#awesome ul li:eq(3)");
不是那么伪:-)我需要相同的,我做了一个例子,在这里查看http://jsfiddle.net/jeduarz/f88u9u9p/1/
HTML:
Please press intro to select the item in the list
- I am wating a coffee
- I am wating a icecream
- I am wating a model girlfriend
- I am wating a jirafe
- I am wating a pankace
You selected value is hereCSS:
ul { background:#F9F9F9); } ul:focus { outline:solid 1px green; } .thisList { list-style-type:none; padding:5px; } .thisList li { border-bottom:1px solid #CCC; padding:3px 5px; } li:focus { outline:solid 1px #F90; } div { border: 1px solid #CCC; margin-top:20px; height:50px; } p{ background: #FE0; padding:5px; margin:10px 0; width:100%; }
JS(使用jQuery):
$(document).keyup(function (event) { var keycode = (event.keyCode ? event.keyCode : event.which); tab_on = $(':focus').attr('tabindex'); // SCAPE if (keycode == 27) { $(':focus').blur(); } if (keycode == 40) { // DOWN if (tab_on == -2) { li = $(':focus').next().is('li'); if (li) $(':focus').next().focus(); else { $('.thisList li:first-child').focus(); } } } if (keycode == 38) { // UP if (tab_on == -2) { li = $(':focus').prev().is('li'); if (li) $(':focus').prev().focus(); else { $('.thisList li:last-child').focus(); } } } // INTRO if (keycode == 13) { content = $(':focus').html(); $('div').html(content); } });