私は jQuery を使って遊んで (読み: 最初の進出)、簡単なメモを取るアプリケーションを作成しています。現在、データベース ala ajax からコンテンツを取得し、それをページに挿入しています。ただし、動的コンテンツ (保存ボタン) で .click() の単純なコールバックを実行しようとすると、機能しません。その意図は、コンテンツをデータベースに戻して保存することです。
jquery を動的に作成しているのと同じコンテンツを取得し、それを Web サーバーが送信している HTML に静的に投げ込むと、機能します。なぜ一方が機能し、もう一方が機能しないのかわかりません。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<link rel="stylesheet" type="text/css" href="layout.css" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<!--Get notes out of database and show them-->
<script type="text/javascript">
$(function()
{
$.ajax({
url: 'noteGet.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows) {
var noteId = rows[i][0];
var noteContent = rows[i][2];
$('#allNotes')
.append('<span id="stickyNote'+noteId+'" class="stickyNote"><textarea id="stickyNoteTextArea'+noteId+'" class="stickyNoteTextArea">'+noteContent+'</textarea><a href="#" id="stickyNoteSave'+noteId+'">save</a></span>')
}
}
});
//works
$('#stickyNoteSave1').click(function() {
alert("save button clicked");
});
//does not work
$('#stickyNoteSave13').click(function() {
alert("save button clicked");
});
});
</script>
<!--
<script type="text/javascript">
$('#noteForm').submit(function(event) {
event.preventDefault();
$.post("notePost.php", $('#noteTextArea').serialize(), function(data) {
alert(data);
});
});
});
</script>
-->
</head>
<body>
<span id="allNotes">
<!---The .click callback with the jquery selector works for only this span!-->
<span id="stickyNote1" class="stickyNote"><textarea id="stickyNoteTextArea1" class="stickyNoteTextArea">fake</textarea><a href="#" id="stickyNoteSave1">special save</a></span>')
</span>
</body>
</html>