我正在使用jQuery播放(阅读:初步尝试)并制作一个简单的笔记应用程序。现在,我正在从数据库ala ajax中提取内容并将其插入到页面中。 但是,当我尝试对动态内容(保存按钮)执行简单的.click()回调时,它不起作用。目的是将内容发送回数据库以进行存储。
如果我采用相同的内容,我正在动态地将jquery掀起,并且只是在网络服务器发送的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>
答案 0 :(得分:2)
绑定事件时,事件将附加到选择器匹配的DOM元素。如果该元素尚不存在,则不会绑定任何内容。
解决方案是使用委托:
$('#container').on('click', '.elementselector', function() {
})
#container
应该是一个包含新插入元素的元素(可能是document
,但更具体的东西更好),而.elementselector
应该是一个匹配您实际想要的元素的选择器事件,例如#stickyNoteSave13
答案 1 :(得分:1)
// live
$('#stickyNoteSave13').live('click',function(){/*...*/});
或
// on
$('#stickyNoteSave13').on('click',function(){/*...*/});
或
// delegate
$('sticky-notes-container-selector').delegate('#stickyNoteSave13','click',function(){/*...*/});
我看到你使用jQuery 1.7+,所以我推荐使用'on'方法,如下所示:
$('sticky-notes-container-selector').delegate('click','#stickyNoteSave13',function(){/*...*/});
答案 2 :(得分:0)
使用live
:
$('#stickyNoteSave13').live('click',function() {
alert("save button clicked");
});
答案 3 :(得分:0)
jQuery 1.7之后不建议使用jQuery,所以你应该使用on()
$(document).on('click', '#stickyNoteSave13', function(){/*...*/});