본문 바로가기
JavaScript, jQuery, Java

Sortable 사용하기 (Drag and Drop 순서 변경)

by 보리하늘 2017. 12. 20.
728x90
반응형

동적으로 만든 <li> 를 드래그 앤 드롭으로 순서를 변경하려 했었다.

appenChild 를 하다보니 맨 마지막에 가서 붙고, 어느곳에 붙여야 하는지 순서를

어떻게 정해줄까 고민하다가 Sortable 을 이용하는게 나을 것 같아 방법을 바꾸었다.


jQuery UI를 이용하여 초보자도 쓸 수 있는 간편한 기능이다.



1
2
3
4
5
6
<dt>검색항목</dt>
<dd>
    <div style="width:160px; height:100px">
        <ul class="make_lst" id="addFind_column"></ul>
    </div>
</dd>
cs





*** jsp 단 에서 div 와 ul 만 정의해 준 뒤 동적으로 만든 li 를 ul 에 붙인다.


1
2
3
4
if(oChoice.eq(i).attr('class'== "activation"){
    $("#"+id.substring(0,7)+"_column").append("<li><a href='#' id='ml_"+i
    +"'>"+oChoice.eq(i).text()+"</a></li>");
}
cs




사실 위의 소스들은 리스트를 만들기 위한 것이기 때문에 별로 중요한 것은 아니다.

ul 의 id 값만 있으면 Sortable 의 사용이 가능하다.




*** jsp 의 상단 head 안쪽에 스크립트와 css 코드를 넣는다.

(기존에 로드한 jquery.js 또는 적용할 style 이 있는경우 필요없는 소스는 지워도 된다. function 부분은 필수! )



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
 
<style>
 
  #sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
  #sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
  #sortable li span { position: absolute; margin-left: -1.3em; }
 
</style>
 
<script>
 
  $(function() {
 
    $( "#addFind_column" ).sortable();
 
    $( "#addFind_column" ).disableSelection();
 
  });
 
</script>
cs





** 조정한 리스트를 배열에 넣어 순서대로 저장한다.


1
2
3
4
5
6
7
var obj = document.getElementsByTagName("li");
 
  if( obj.length >= 0 ){
    var orderList = "";
 
    for(var i=0; i<obj.length; i++) orderList += obj[i].id + "^";
  }
cs




 

** 사이트 참조 : http://jqueryui.com/sortable/

728x90
반응형

댓글