动态 Django 内联表单集使用纯 JavaScript

huangapple go评论78阅读模式
英文:

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(&#39;#add-image-button&#39;);
btnAddMoreImg.addEventListener(&#39;click&#39;, (evt) =&gt; {
    evt.preventDefault();
    let count = document.querySelector(&#39;#item-images&#39;).children.length;
    let tmplMarkup = document.querySelector(&#39;#images-template&#39;).innerHTML;
    let compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
    
    $(&#39;#item-images&#39;).append(compiledTmpl); // how to convert this to pure javascript?

    // update form count
    document.querySelector(&#39;#id_images-TOTAL_FORMS&#39;).setAttribute(&#39;value&#39;, count + 1);
})

This works but there is still this jquery code $(&#39;#item-images&#39;).append(compiledTmpl) which I tried to change to document.querySelector(&#39;#item-images&#39;).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;

huangapple
  • 本文由 发表于 2023年6月1日 23:11:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定