好吧,我在这里创建评论系统。如果已经有至少一条评论,但是如果没有评论并尝试创建一条评论,则它会正常工作,这比向我显示在TypeError异常上暂停的错误:document.getElementById(...)为null。我不知道该如何解决。
html
<div id="post_id" post-id="{{post.pk}}" post-slug="{{post.slug}}">
{% if node.level < 3 %}
<button class='btn btn-success' onclick="myFunction({{node.id}})">Reply</button>
{% endif %}
</div>
jQuery,ajax功能
$(document).on('click', '#newcomment, #newcommentinner', function (e) {
e.preventDefault();
var button = $(this).attr("value");
var post_id = document.getElementById('post_id').getAttribute('post-id'); #Here is an error appearing.
var post_slug = document.getElementById('post_id').getAttribute('post-slug');
console.log(post_id,'postid')
var placement = "commentform"
if (button == "newcommentform") {
var placement = "newcommentform"
}
$.ajax({
type: 'POST',
url: '{% url "posts:addcomment" %}',
data: $("#" + button).serialize() + "&post_id="+post_id + "&post_slug="+post_slug,
cache: false,
error: console.log('post_id' + post_id),
success: function (json) {
console.log(json)
$('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \
<div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \
<div>' + json['result2'] + '</div> \
<hr> \
</div>').insertBefore('#' + placement);
$('.commentform').trigger("reset");
formExit()
},
error: function (xhr, errmsg, err) {
}
});
})
如果需要更多的代码而不是在评论会话中告诉我。我将用该信息更新我的问题。
我不知道您为什么要用纯JS弄乱jQuery synthax?:)var post_id = $('#post_id').attr('post-id')
应该做到这一点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句