[英]jQuery event not triggering
当用户单击“提交”按钮发表评论时,我试图触发发布请求。 现在单击提交按钮不会触发任何操作,我什至试图console.log($(this))我没有任何输出。 下面的第一个代码是jQuery事件代码和ajax代码。 下面的代码块是html按钮。 谢谢您的帮助。
$('#submitComment').on('click', '#content', function() {
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: data = { comment: {
body: $(this).find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: 2}
}
}).done(function(response) {
console.log(response);
});
});
我试图以jQuery事件为目标的按钮
<div class="container">
<div id="content">
//the code between comments is in a Handelbar template
<input name="createComment">
<button type="submit" id="submitComment">Create Comment</button>
//end of handelbar template
</div>
</div>
您需要将委托的处理程序绑定到目标元素( submitComment
)的祖先( #content
)
$('#content').on('click', '#submitComment', function () {
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: data = {
comment: {
body: $(this).find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: 2
}
}
}).done(function (response) {
console.log(response);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.