目标是在左兄弟或其同胞之前移动一个元素.
<ul> <li>One</li> <li>Two</li> <li>Three</li> <li>One</li> </ul>
只给出元素的索引,我需要将其移动到左或右.说索引是1(LI和“Two”作为innerText),那么我想把它移动到左边,输出应该是:
<ul> <li>Two</li> <li>One</li> <li>Three</li> <li>One</li> </ul>
解决方法
/** * @param siblings {jQuery} List of sibling elements to act upon * @param subjectIndex {int} Index of the item to be moved * @param objectIndex {int} Index of the item to move subject after */ var swapElements = function(siblings,subjectIndex,objectIndex) { // Get subject jQuery var subject = $(siblings.get(subjectIndex)); // Get object element var object = siblings.get(objectIndex); // Insert subject after object subject.insertAfter(object); } $(function() { swapElements($('li'),1); });