我列出了要完成的任务的“待办事项清单”。我有一些按钮可以在列表中上下移动任务。

我去了向上和向下按钮。我唯一的问题是任务div能够上下移动整个页面。如何使任务div只能上下移动?

谢谢!

这是我的代码:



$(document).ready(function(){

	$('.up_button').click(function(){
		$(this).parents('.task').insertBefore($(this).parents('.task').prev());
	});

	$('.down_button').click(function(){
		$(this).parents('.task').insertAfter($(this).parents('.task').next());
	});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="task col-sm-12">
	<div class="col-md-6">
		 <div class="input-group">
			<span class="input-group-addon"><input type="checkbox" name="task1" value="taskID1" /></span> <input type="text" class="form-control" value="Write HTML" readonly>
		</div>
	</div>
	<div class="col-md-6">
		<button type="button" class="btn btn-default up_button"><span class="glyphicon glyphicon-arrow-up"></span> Move Up</button>
		<button type="button" class="btn btn-default down_button"><span class="glyphicon glyphicon-arrow-down"></span> Move Down</button>
	</div>
</div>

<div class="task col-sm-12">
	<div class="col-md-6">
		 <div class="input-group">
			<span class="input-group-addon"><input type="checkbox" name="task1" value="taskID1" /></span> <input type="text" class="form-control" value="Write XML" readonly>
		</div>
	</div>
	<div class="col-md-6">
		<button type="button" class="btn btn-default up_button"><span class="glyphicon glyphicon-arrow-up"></span> Move Up</button>
		<button type="button" class="btn btn-default down_button"><span class="glyphicon glyphicon-arrow-down"></span> Move Down</button>
	</div>
</div>

最佳答案

1st:我认为您需要先定义$(this),然后再插入insertAfter或insertBefore

第二:您可以使用.closest()

$(document).ready(function(){

    $('.up_button').click(function(){
        var ThisIt = $(this);
        $(this).closest('.task').insertBefore(ThisIt.closest('.task').prev('.task'));
    });

    $('.down_button').click(function(){
        var ThisIt = $(this);
        ThisIt.closest('.task').insertAfter(ThisIt.closest('.task').next('.task'));
    });

});


Demo Here

07-26 09:33