我正在使用jQuery并制作一个简单的笔记应用程序。现在,我正在从数据库中提取内容并将其插入到页面中。但是,当我尝试对动态内容(保存按钮)上的.click()进行简单的回调时,它不起作用。其目的是将内容发送回数据库进行存储。
如果我采用jquery动态生成相同内容,并将其静态地放入does服务器正在发送的HTML中,它确实可以工作。我不明白为什么一个可以工作,而另一个不能。
The problematic website
<!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>发布于 2012-04-23 03:12:24
当您绑定一个事件时,该事件被附加到与选择器匹配的DOM元素。如果元素还不存在,则不会绑定任何内容。
解决方案是使用委托:
$('#container').on('click', '.elementselector', function() {
})#container应该是一个包含新插入的元素的元素(可以是document,但更具体的元素更好),.elementselector应该是一个选择器,匹配您实际想要事件的元素,例如#stickyNoteSave13
发布于 2012-04-23 03:11:21
使用delegate、live或on而不是click:
// 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(){/*...*/});发布于 2012-04-23 03:10:48
使用live:
$('#stickyNoteSave13').live('click',function() {
alert("save button clicked");
});https://stackoverflow.com/questions/10271156
复制相似问题