无法在jQuery中向上或向下移动列表中的多个项目
问题描述:
我有jQuery代码中的下列代码,在列表中向上或向下按钮上下移动列表项目。无法在jQuery中向上或向下移动列表中的多个项目
$("#btn-move-up").click(function() {
$item = $(".highlight");
$before = $item.prev();
$item.insertBefore($before);
});
//onclick of move down button, move the item down in the list
$("#btn-move-down").click(function() {
$item = $(".highlight");
$after = $item.next();
$item.insertAfter($after);
});
代码工作的罚款单项目,但如果您选择多个项目,它开始表现unexpectedly.the working fiddle here。 有人可以指出我的代码或其他更好的解决方案中的错误吗?
答
在插入之前需要选择列表中的第一个项目,插入之前需要选择最后一个项目。否则,或者为每个项目后强调之前它会插入:
$("#btn-move-up").click(function() {
$item = $(".highlight");
$before = $item.first().prev();
$item.insertBefore($before);
});
//onclick of move down button, move the item down in the list
$("#btn-move-down").click(function() {
$item = $(".highlight");
$after = $item.last().next();
$item.insertAfter($after);
});
$('ul').on("click", "li", function(e) {
if ($(this).hasClass('highlight')) {
$(this).removeClass('highlight');
} else {
$(this).addClass('highlight');
}
e.stopPropagation();
});
.highlight {
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btn-move-up" class="btn btn-info" data-toggle="tooltip" data-placement="right" title="Up"><i class="fa fa-arrow-up"></i>Up</button>
<button type="button" id="btn-move-down" class="btn btn-info" data-toggle="tooltip" data-placement="right" title="Down"><i class="fa fa-arrow-down"></i>Down</button>
<ul id="fields">
<li>Ist</li>
<li>2nd</li>
<li>3rd</li>
<li>4th</li>
</ul>
Thanku @Fabricator它的工作。 –