【发布时间】:2022-01-12 04:20:40
【问题描述】:
您好,我正在尝试为我的表单集遵循以下教程,但我发现部分问题:
container.insertBefore (newForm, addButton)
出现的错误如下:
calculos.js: 195 Uncaught TypeError: Cannot read properties of undefined (reading 'childNode')
我已经尝试了所有方法但找不到 childNode
JS
let parteForm = document.querySelectorAll(".part-form")
let container = document.querySelector("#part-form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing
addButton.addEventListener('click', addForm)
function addForm(){
//e.preventDefault()
let newForm = parteForm[0].cloneNode(true)
let formRegex = RegExp(`form-(\\d){1}-`,'g')
formNum++
newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)
container.insertBefore(newForm, addButton)
//parentnode.insertbefore(newnode,elnodoantesdelcualseinsertanewnode)
//#part-form-container.insertbefore(div.part-form,)
totalForms.setAttribute('value', `${formNum+1}`)
}
HTML
<form method="POST" id="part-form-container">
{% csrf_token %}
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row mb-3">
<div class="col-md-12">
<div class="mb-3">
<label for="verticalnav-email-input">Summary</label>
{{presupuestosparteform.resumen}}
</div>
</div>
</div>
<h4 class="card-title">Parts list</h4>
<p class="card-title-desc">Add the parts that you need to include.</p>
<input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" />
<div class="table-responsive">
<table class="table table-bordered table-nowrap align-middle" id="childTable1">
<tbody>
{{ formset.management_form }}
{% for form in formset %}
<div class="part-form">
<tr>
<td>
{{form.codigo}}
</td>
<td>
{{form.descripcion}}
</td>
</tr>
</div>
{% endfor %}
</tbody>
</table>
</form>
【问题讨论】:
-
你有
container.insertBefore(newForm, addButton)- 只有当addButton是container的直接子代时才有效,但不是。有一堆未关闭的 div 没有帮助。 -
谢谢!它奏效了
标签: javascript html jquery django