当用户单击评论的提交按钮时,我尝试触发发布请求。现在单击提交按钮不会触发任何内容,我什至尝试 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>
最佳答案
您需要将委托(delegate)处理程序绑定(bind)到目标元素 (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);
});
});
关于javascript - jQuery 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878292/