新卒から文系エンジニア→人材業界に転職した人のブログ

新卒から文系エンジニア→人材業界に転職。技術・スキルがないためブログを通して勉強。その後、IT業界の業界知識が活かせる人材業界へ。異業種×異職種の転職経験有り。

このエントリーをはてなブックマークに追加

【jQuery入門】jQueryありとjQueryなしのソース比較~動的にリスト要素(li)の追加と動的に追加した要素へのイベントの設定・移動など~

【今回の内容】

「以前作成したWebtodoリスト(しょぼい)をjqueryで書き直してみる」

 具体的には
  ①登録:動的にリストの生成
  ②変更:生成したリストを移動する
  ③削除:もしあるステータスに移動したならば次の移動で要素を削除する



 全体感想:やはりあきらかに総コード量が減り、
      ・可読性があがる
      ・ソース量が減った       
     

【以前のソース】


DOMの情報を扱っているところに注目してください。

<!--//////////////////////////////
/////////リスト追加処理///////////
////////////////////////////////-->

function add_list(){
    var add_priority="("+select_option+")";
	var add_text=document.getElementById("add_text").value;
	var list_text=document.createTextNode(add_text+add_priority);
	var new_list=document.createElement("li");
	new_list.appendChild(list_text);
	new_list.id=count;  /*"new_list"+*/
	new_list.setAttribute("onDblClick","moveList(this)");
	new_list.setAttribute("onmouseover","addcolor(this)");
	new_list.setAttribute("onmouseout","defaultcolor(this)");
	document.getElementById("ul_toDo").appendChild(new_list);
	send_db(new_list.id);
	count++;
}



<!--//////////////////////////////
/////////リスト移動処理///////////
////////////////////////////////-->

function moveList(obj){
	var ul_toDo=document.getElementById("ul_toDo");
	var ul_Doing=document.getElementById("ul_Doing");
	var ul_Done=document.getElementById("ul_Done");

<!--どのカテゴリ(todo or doing or done)にあるリストか判定する処理-->
	if("frame_toDo"==obj.parentNode.parentNode.id){
		var clone=obj.cloneNode(true);
		ul_Doing.appendChild(clone);
		ul_toDo.removeChild(obj);
		send_db(clone.id);
		
	}
		else if("frame_Doing"==obj.parentNode.parentNode.id){
			var clone=obj.cloneNode(true);
			ul_Done.appendChild(clone);
			ul_Doing.removeChild(obj);
			send_db(clone.id);
		}
			else{
			send_db(obj.id);
			ul_Done.removeChild(obj);
			
			}
}

【今回のやることを整理】

 ①登録:リストの登録
  テキストボックスに入力された値をリストに追加する
  
  ①指定のul要素を取得
  ②追加するli要素を生成
  ③①で取得したul要素の配下に追加する



 ②変更と削除:リストのステータスの変更

   
  ①リスト生成時にli要素にイベントを設定する
→リスト生成時にイベントの追加では、イベントを認識してくれない。
    (jQuery読み込み時にまだ追加される要素がないため)
    対策:onメソッドで解決。

   例:対象範囲.on(イベント名,対象セレクタ,処理内容)という感じ

     $(document).on('click','#list1',function(){
		alert("");
		})


   参考:jQuery入門
   いくつかサイトを見ましたが、一番わかりやすかったです。
  

       

②親要素の取得(自分がどのカテゴリーにいるか)

$(this).parent().attr('id')で取得


 ③親要素の値によって条件分岐を行う
    →ステータスごとにdivのidをふり、条件分岐を行った


		$(document).on('click','.lists',function(){
			if($(this).parent().attr('id')=="sq1"){
				$(this).prependTo('#sq2');
				}
			
			else if($(this).parent().attr('id')=="sq2"){
					$(this).prependTo('#sq3');
				}
			else{
				$(this).remove();
				}
				
		})        
            

jQueryに変更後のソース】

<!DOCTYPE html>
<html lang="ja">

<html>
<head>
	<meta charset="utf-8">
	<title>jquery</title>
	<link rel="stylesheet" type="text/css" href="./style.css">
	
</head>
<body>
<input type="text" id="input" value=""></input>
<input type="button" id="bt" value="追加"></input>
<div>
<h2 class="ct" id="ct1">Todo</h2>
<h2 class="ct" id="ct2">Doing</h2>
<h2 class="ct" id="ct3">Done</h2>
</div>
<div id="ssq1">
<div id="sq1"></div>
<div id="sq2"></div>
<div id="sq3"></div>

</div>
	<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
	<script>
	var i=0;
	$(function(){
	
	//リスト追加する追加するイベントを定義
		$('#bt').click(function(){
			var addList=$('<li>').text($('#input').val())
			.attr('id',"list"+i)
			.addClass('lists');
			$('#sq1').prepend(addList);
		i++;
		});
		
	//追加した要素のイベントを定義
		$(document).on('click','.lists',function(){
			if($(this).parent().attr('id')=="sq1"){
				$(this).prependTo('#sq2');
				}
			
			else if($(this).parent().attr('id')=="sq2"){
					$(this).prependTo('#sq3');
				}
			else{
				$(this).remove();
				}
				
		})

});
</script>
</body>
</html>
.hatena-module:nth-of-type(10) { background: transparent; } .hatena-module:nth-of-type(10) .hatena-module-title{ display: none; } .hatena-module:nth-of-type(10) .hatena-module-body { padding: 0; }