因异常TypeError而暂停:document.getElementById(..)为null



好吧,我正在创建注释系统。如果已经有至少一个注释,它可以正常工作,但如果没有注释并尝试创建一个,它会显示一个错误异常时暂停类型错误: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语法?:(

var post_id = $('#post_id').attr('post-id')

应该这样做。

最新更新