未捕获的类型错误:无法读取属性'拆分'的未定义(匿名函数)

Uncaught TypeError: Cannot read property 'split' of undefined(anonymous function)

本文关键字:拆分 未定义 函数 属性 类型 错误 读取      更新时间:2023-09-26

我不知道为什么会出现这个错误,我只是想把在索引页中工作的表单移到发布页。我只是简单地移动了表单,但没有工作;Uncaught TypeError:由于某种原因,无法读取未定义(匿名函数)的属性"split"。

            <div>
        {% crispy comment_form comment_form.helper %}
                </div>
<script>
$(document).ready(function() {

     $(document).on('submit', 'form', function(e){
      e.preventDefault();
      if($(this).parents("tr").length != 0) {
        parent_id = $(this).parents("tr").attr("id").split("_")[1];
        data_str = $(this).serialize() + "&parent_id=" + parent_id;
      } else {
        data_str = $(this).serialize();
      }
      $.ajax({
        type:'POST',
        url:'/comment/create/',  // make sure , you are calling currect url
        data:data_str,
        success:function(json){              
          alert(json.message); 
          if(json.status==200){
             var comment = json.comment.trim();
             var user = json.user;
             /// set `comment` and `user` using jquery to some element
              if(!json.parent) {
                $(comment).insertBefore('.table tr:first');
              }
              else {
                $(comment).insertBefore('#comment_' + json.parent_id + ' #child_comment:first');
                $(".replies").text("reply" + json.comment_count + "see");
              }
           }  
        },
        error:function(response){
          alert("some error occured. see console for detail");
        }
      });
    });

我的表格

class CommentForm(forms.Form):
    comment = forms.CharField(
        widget=forms.Textarea(attrs={"placeholder": "leave"})
    )
    #hidden_field = forms.CharField(widget=forms.HiddenInput())
    def __init__(self, hidden_data=None, data=None, files=None, **kwargs):
        super(CommentForm, self).__init__(data, files, kwargs)
        self.helper = FormHelper()
        self.helper.form_show_labels = False
        self.helper.add_input(Submit('submit', css_class='btn btn-default'))
        if hidden_data:
            self.helper.add_input(Hidden('post_id', hidden_data['post_id']))
            self.helper.add_input(Hidden('origin_path', hidden_data['origin_path']))
            if hidden_data.get('parent_id', None):
                self.helper.add_input(Hidden('parent_id', hidden_data['parent_id']))
'

我的观点

  def comment_thread(request, id):
        comment = Comment.objects.get(id=id)
        comments = comment.post.commented_post.all()
        for c in comments:
                c.get_children()
        hidden_data = {
                    "post_id" : comment.post.id,
                    "origin_path" : request.get_full_path,
                    "parent_id" : None
                }
        comment_form = CommentForm(hidden_data=hidden_data) 
        context = {
        "comment": comment,
        'comment_form':comment_form
        }
        return render(request, "comments/comment_thread.html", context)

编辑:

{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<a href="{{ comment.get_origin }}">Go Back</a>
<table class='table'>
<tr><td>{{ comment.get_comment }} 
<br/><small>via {{ comment.user }} | {{ comment.timestamp|timesince }} ago </small>
                {% if not comment.is_child %}
                <ul>
                {% for child in comment.get_children %}
                <li>{{ child.get_comment }} 
                <small>via {{ child.user }}</small>

                </li>
                {% endfor %}
                </ul>
                <div>
        {% crispy comment_form comment_form.helper %}
                </div>
                {% endif %}

</td></tr>

</table>
<script>
$(document).ready(function() {

     $(document).on('submit', 'form', function(e){
      e.preventDefault();
      if($(this).parents("tr").length != 0) {
        parent_id = $(this).parents("tr").attr("id").split("_")[1];
        data_str = $(this).serialize() + "&parent_id=" + parent_id;
      } else {
        data_str = $(this).serialize();
      $.ajax({
        type:'POST',
        url:'/comment/create/',  // make sure , you are calling currect url
        data:data_str,
        success:function(json){              
          alert(json.message); 
          if(json.status==200){
             var comment = json.comment.trim();
             var user = json.user;
             /// set `comment` and `user` using jquery to some element
              if(!json.parent) {
                $(comment).insertBefore('.table tr:first');
              }
              else {
                $(comment).insertBefore('#comment_' + json.parent_id + ' #child_comment:first');
                $(".replies").text("reply" + json.comment_count + "view all");
              }
           }  
        },
        error:function(response){
          alert("some error occured. see console for detail");
        }
      });
    });

$(this).parents("tr").attr("id")在尝试设置parent_id变量时返回undefined。我看到在您的视图中,您传入了"parent_id":None。HTML是什么样子的?我认为元素应该有一个jQuery要获取的ID,而您没有在视图中设置它。如果是这样,您可以检查if ($(this).parents('tr').attr('id')) { /* split in here */ }