我有一个AJAX方法,它正在为正在单击的链接触发一个DELETE方法,但是尽管我的jQuery工作过一次,但我还没有达到触发AJAX方法的程度,并且无法确定代码的错误所在。可能是因为语法错误。onload console.log会触发,因此我知道文件是被识别的,但是单击中的console.log没有触发。此外,这是触发DELETE方法的最佳方法吗?
这里是jQuery:
window.onload = function() {
console.log("Window loaded")
$('#blog-comment-delete').click(function(){
var blogId = $(this).data("blog-id");
var commentId = $(this).data("comment-id");
var urlPath = '/app/blog/' + blogId + '/comment/' + commentId;
console.log('Pre-AJAX');
$.ajax({
method: 'DELETE',
url: urlPath,
success: function(){
window.location.replace('/app');
},
error: function(error){
console.log('Deletion Error: ' + error);
}
});
});
};使用应用程序路由Node.js:
appRoutes.route('/blog/:blogId/comment/:blogCommentId')
.delete(function(req, res){
models.BlogComment.destroy({
where: {
blogId: req.params.blogId,
blogCommentId: req.params.blogCommentId,
userId: req.user.userId
}
}).then(function(){
req.flash('info', 'Comment was successfully deleted.');
res.send('Comment was deleted.');
});
});链接:
<div class="blog-comments">
{{#blog_comments}}
<p id="blog-comment">{{comment}}</p>
<a href="#" id="blog-comment-delete" data-blog-id="{{blogId}}" data-comment-id="{{blogCommentId}}">Delete</a>
{{/blog_comments}}
</div>发布于 2017-01-14 20:55:14
而不是id的,使用类名作为选择器。id是唯一的,如果同一个页面上有多个具有相同id的元素,那么您的事件侦听器就会中断。因此,取而代之的是:
<div class="blog-comments">
{{#blog_comments}}
<p id="blog-comment">{{comment}}</p>
<a href="#" class="blog-comment-delete" data-blog-id="{{blogId}}" data-comment-id="{{blogCommentId}}">Delete</a>
{{/blog_comments}}
</div>您的事件侦听器应该如下所示:
$('.blog-comments').on('click', '.blog-comment-delete', function(){
});发布于 2017-01-14 20:51:13
你可以这样试一试
$('#blog-comment-delete').on('click',function(){
//Your code
});2)如果第一次没有工作,则:
$( "body" ).on( "click", "#blog-comment-delete", function() {
//Your code
}); 3)
$('body').delegate('#blog-comment-delete','click',function(){
//Your code
});https://stackoverflow.com/questions/41654725
复制相似问题