Tom*_*kay 6 javascript jquery dom html-lists
什么是很酷的方式来应用它?我需要一个在<ul>中交换两个<li>位置的脚本.它认为应该有可能实现.感谢您的答复.
HTML
<div id="awesome">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
伪Javascript(JQuery)
$("#awesome ul li:eq(1)").exchangePostionWith("#awesome ul li:eq(3)");
Run Code Online (Sandbox Code Playgroud)
HTML结果
<div id="awesome">
<ul>
<li>Item 1</li>
<li>Item 4</li>
<li>Item 3</li>
<li>Item 2</li>
<li>Item 5</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
Dav*_*ang 27
你可以使用jQuery .after()来移动元素.我克隆了其中一个,所以原来可以作为占位符.这就像如果你想切换变量a和b,你需要第三个临时变量.
$.fn.exchangePositionWith = function(selector) {
var other = $(selector);
this.after(other.clone());
other.after(this).remove();
};
Run Code Online (Sandbox Code Playgroud)
现在你的伪代码$("#awesome ul li:eq(1)").exchangePositionWith("#awesome ul li:eq(3)");不是那么伪:-)