英文:
Dynamic django inline_formset using pure javascript
问题
我在搜索有关Django inline_formset与JavaScript的工作示例时发现了这篇帖子:https://stackoverflow.com/questions/21260987/add-a-dynamic-form-to-a-django-formset-using-javascript-in-a-right-way。在此过程中,我尝试将JQuery部分转换为纯JavaScript?我已经尝试过以下代码:
const btnAddMoreImg = document.querySelector('#add-image-button');
btnAddMoreImg.addEventListener('click', (evt) => {
evt.preventDefault();
let count = document.querySelector('#item-images').children.length;
let tmplMarkup = document.querySelector('#images-template').innerHTML;
let compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
// 将下面这行代码从jQuery转换为纯JavaScript
// $('#item-images').append(compiledTmpl);
document.querySelector('#item-images').insertAdjacentHTML('beforeend', compiledTmpl);
// 更新表单计数
document.querySelector('#id_images-TOTAL_FORMS').setAttribute('value', count + 1);
})
这段代码有效,但仍然包含了这个jQuery代码$('#item-images').append(compiledTmpl)
。我尝试将其更改为document.querySelector('#item-images').append(compiledTmpl)
,但最终的结果将是一串HTML标签而不是一个新的表单添加进去。
英文:
I was searching on working examples for django inline_formset with javascript and found this post <https://stackoverflow.com/questions/21260987/add-a-dynamic-form-to-a-django-formset-using-javascript-in-a-right-way>. In the process, I tried to convert the Jquery portion into pure javascript? I have tried
const btnAddMoreImg = document.querySelector('#add-image-button');
btnAddMoreImg.addEventListener('click', (evt) => {
evt.preventDefault();
let count = document.querySelector('#item-images').children.length;
let tmplMarkup = document.querySelector('#images-template').innerHTML;
let compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
$('#item-images').append(compiledTmpl); // how to convert this to pure javascript?
// update form count
document.querySelector('#id_images-TOTAL_FORMS').setAttribute('value', count + 1);
})
This works but there is still this jquery code $('#item-images').append(compiledTmpl)
which I tried to change to document.querySelector('#item-images').append(compiledTmpl)
, but the end result would be a string of html tags instead of a new form added.
答案1
得分: 0
使用表格的insertRow()
方法使其正常工作。
let newRow = itemContainer.insertRow(itemContainer.rows.length);
newRow.outerHTML = compiledTmpl;
英文:
Got this working using the insertRow() method of a table.
let newRow = itemContainer.insertRow(itemContainer.rows.length);
newRow.outerHTML = compiledTmpl;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论