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

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

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

【Javascript・DOM】動的なリストの作成とイベントハンドラの組み合わせ②

前回の動的なリストの追加に少し変更しました。

 

変更内容は、

 

「選択したリストにリストを追加していくという」

 

ものです。

 

 

最初からきめうちで追加するリストがあるのではなく、ユーザが選択したリストにリストを追加するというように変更しました。

 

 

【処理の流れ】

1、プルダウンを変更したときにイベントハンドラから選択したリスト名を取得

2、リストを追加するfunctionに引数として、「1で選択したリスト名」を渡す

3、リストを追加するfunctionにより、選択したリストにリストが追加される

 

【所感】

 

イベントハンドラの使いどころについて」

イベント=functionを呼ぶではない。

いままでイベントハンドラといったら、Onclick=add()とかonmouseover=changecolor()かと思ってたけど、

 

今回のようにユーザが何かアクションを起こしたら

 

その値をどこか(変数)に持っておき、違うイベントハンドラで使用するというのも良い!!

 

ということに気がつけたのは非常によかった。

 

例)onChange="select_list=this.options[this.selectedIndex].value

 

 

【参考ソース】

 

 

<html>

<head></head>

<body>

<h2>リストを追加していく部品</h2>

<select onChange="select_list=this.options[this.selectedIndex].value" size="1">

<option value="" ></option>

<option value="list1" >リスト1</option>

<option value="list2" >リスト2</option>

<input type="text" value="" id="Input_str">

<input type="button" value="追加"onclick="add(select_list)"><br>

<script Language="JavaScript" type="text/javascript">

function add(select_list){

var list_value=document.getElementById("Input_str").value;

var list_text=document.createTextNode(list_value);

var new_list=document.createElement("li");

new_list.appendChild(list_text);

document.getElementById(select_list).appendChild(new_list);

}

 

</script>

 

<ul id="list">

 

</ul>

 

</br>

 

</br>

 

</br>

 

</br>

 

</br>

 

</br>

 

<ul id="list1">

 

</ul>

 

</br>

 

</br>

 

</br>

 

</br>

 

</br>

 

</br>

 

<ul id="list2">

 

</ul>

 

</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; }