Javascript jQuery事件未触发
我试图在用户单击submit按钮获取评论时触发post请求。现在单击submit按钮不会触发任何内容,我甚至尝试了console.log($(this))我没有得到任何输出。下面的第一个代码是jQuery事件代码和ajax代码。下面的代码块是html按钮。谢谢你的帮助Javascript jQuery事件未触发,javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,我试图在用户单击submit按钮获取评论时触发post请求。现在单击submit按钮不会触发任何内容,我甚至尝试了console.log($(this))我没有得到任何输出。下面的第一个代码是jQuery事件代码和ajax代码。下面的代码块是html按钮。谢谢你的帮助 $('#submitComment').on('click', '#content', function() { $.ajax({ url: 'http://localhost:3000/
$('#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>
//注释之间的代码位于Handelbar模板中
创建注释
//手杖模板末端
您需要将委托处理程序绑定到目标元素(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);
});
});