我正在使用jQuery为Symfony 4中的另一个表单中的表单集合添加和删除表行 . 这并不容易,但最终使它工作 . 使用Twig中的宏,我可以得到这个渲染结果:
<table>
<div id="document-list" data-prototype="
<tr>
<td>
<fieldset class="form-group">
<div id="program_programDocument___name__" novalidate="novalidate">
<div class="form-group"><input type="text" id="program_programDocument___name___name" name="program[programDocument][__name__][name]" required="required" class="form-control"/>
</div>
</div>
</fieldset>
</td>
<td>
<button type="button"class="remove-collection-widget"data-list="#remove-collection-widget">Remove</button>
</td>
</tr>" data-widget-tags="<div></div>">
</div>
</table>
<button type="button" class="add-another-collection-widget" data-list="#document-list">Add document</button>
我尽可能地清理了这段代码以使其可读 . data-prototype="...."
中的所有HTML都应该是这样的 . 我的代码与一些jQuery一起工作(ish):
jQuery('.add-another-collection-widget').click(function(e) {
var list = jQuery(jQuery(this).attr('data-list'));
// Try to find the counter of the list or use the length of the list
var counter = list.data('widget-counter') | list.children().length;
// grab the prototype template
var newWidget = list.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/__name__/g, counter);
// Increase the counter
counter++;
// And store it, the length cannot be used if deleting widgets is allowed
list.data('widget-counter', counter);
// create a new list element and add it to the list
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
newElem.appendTo(list);
});
$(function() {
$(document).on("click", ".remove-collection-widget", function() {
$(this).closest("tr").remove();
});
});
问题是,添加更多表单行时呈现的结果是它们实际上不会在表中结束 . 你可以自己看看(JSFiddle)结果看起来没问题,但实际上并非如此 .
我很确定它与我的jQuery有关,但我现在卡住了,希望你们中的一些人可以指出什么是错的 .
1 回答
将一个
div
作为table
的直接子项,将它绊倒了 .将
id="document-list" data-prototype="...
移动到table
元素摆脱
div
table
将
data-widget-tags
更改为tr
而不是div
从
data-prototype
删除包装tr
解决方案
文档
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table(参见允许的内容)