jQuery を学習していますが、.on()
イベント ハンドラーに問題があります。done
動的に追加された新しいリスト項目にクラスが追加されない理由がわかりません。任意の支援をいただければ幸いです。
jsフィドル
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
ul li{
list-style: none;
}
.done{
text-decoration: line-through;
color: red;
}
.green{
color:green;
}
</style>
</head>
<script type="text/javascript">
$(document).ready(function(){
$('#taskText').keydown(function(evt){
if(evt.keyCode == 13){
addTask(this, evt);
}
});
$('#addTask').click(function(evt){
addTask(document.getElementById('taskText'), evt);
});
//the problem is the code below//
$('#tasks li').on("click", function(evt){
$(this).addClass('done');
});
});
function addTask(textBox, evt){
evt.preventDefault();
var taskText = textBox.value;
$("<li>").text(taskText).appendTo('#tasks');
textBox.value = '';
};
</script>
<body>
<ul id = "tasks">
</ul>
<input type= 'text' id ='taskText'>
<input type = 'submit' id ="addTask" />
<div class = "green"> green text</div>
</body>
</html>