javascript - jQuery 事件未触发

标签 javascript jquery html ajax

当用户单击评论的提交按钮时,我尝试触发发布请求。现在单击提交按钮不会触发任何内容,我什至尝试 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/

相关文章:

javascript - 为什么这个二维数组会出错?

javascript - JQuery 文件上传,到哪里去了?

javascript - 如果值与 master 匹配,则替换文本框的值,然后替换为 yes,否则替换为 no

html - Bootstrap 网格列划分不起作用

javascript - 如何在div上制作悬停效果

javascript - Jupyter notebook 用不同的颜色为不同的括号着色

javascript - ng2-smart-table 将 'Add New' 按钮事件绑定(bind)到外部按钮

javascript - 获取和删除数组中的数据 in array

javascript - Google Closure 编译器发出警告 : incompatible types; even when parameters have common types, 有没有办法解决这个问题?

javascript - 路口观察器(滚动动画)不工作