【问题标题】:Paused on exception TypeError: document.getElementById(...) is null因异常 TypeError 暂停:document.getElementById(...) is null
【发布时间】:2021-02-08 20:54:18
【问题描述】:

好吧,我在这里创建评论系统。如果已经至少有一条评论,它工作正常,但如果没有评论并尝试创建一个,它会向我显示一个错误 Paused on exception TypeError: document.getElementById(...) is 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) {
      }
    });
  })

如果需要更多代码而不是在评论会话中告诉我。我会用这些信息更新我的问题。

【问题讨论】:

    标签: javascript html django ajax django-templates


    【解决方案1】:

    我想知道你为什么要把 jQuery 语法和普通的 JS 混为一谈? :)

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

    应该这样做。

    【讨论】:

      猜你喜欢
      • 2014-10-13
      • 1970-01-01
      • 2012-12-02
      • 2017-10-24
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      相关资源
      最近更新 更多