0

正如标题所述,我的页面上有一个 django 可选择的自动完成表单字段,我试图在页面加载后动态克隆。克隆部分有效,但自动完成字段不起作用。我不知道 django-selectable 的内部结构,而且我还在学习 jQuery,所以我迷失了如何“修复”自动选择功能。

我的一般方法是:我在 div 容器内使用 django 模板变量呈现表单小部件,然后克隆 div 容器。

HTML

<div class="autocomplete" id="autocomplete_{{ form.instance.id}}">{{form.autocomplete_dropdown}}</div>

jQuery

// This works, just the cloned form lacks "autocomplete" functionality.
var autocompleteArray = theDiv.find('.autocomplete');
var acClone = autocompleteArray.clone();
table.find(".column").append(acClone);

动态克隆的自动完成表单的屏幕截图 根据 SunnySydeUp 的评论,我做了以下修改:

jQuery

// Clone the div and all its contents
var acClone = autocompleteArray.clone(true, true);
// Get the children of the div
var acCloneChildrenArray = acClone.children();
// iterate through the children array, modify ids where they exist to make them unique
// e.g., unique id contained in idSuffix.
for (var i = 0; i < acCloneChildrenArray.length; i++) {
    // if it has an id, make it unique
    if (acCloneChildrenArray[i].getAttribute('id')) {
        var ident = acCloneChildrenArray[i].getAttribute('id')
        acCloneChildrenArray[i].setAttribute('id', ident+'_'+idSuffix);
    };
};

现在数据和事件被复制,但它们与原型/主下拉列表相关联。也就是说,单击其中一个克隆对象实际上会触发主对象的下拉列表。我想问题归结为如何将事件处理程序动态附加到新的下拉列表中?

最终工作代码(根据 SunnySydeUp 的解决方案,有一个小错误——下拉按钮重复,但自动完成和下拉功能有效)。

jQuery

// Clone the div
// We leave clone deepcopy flags at default==false
var acClone = autocompleteArray.clone();

// Get the children of the div
// You don't need to set unique id's on the children, it's irrelevant.

// Bind the new selectable fields to the event handlers.
window.bindSelectables('body');
4

1 回答 1

1

我以前没有使用django-selectable过,但我猜它使用 javascript/jQuery 来使自动完成工作。当您调用时clone,它不会克隆下拉列表的 javascript。尝试做:

var acClone = autocompleteArray.clone(true);

传入 true 将使 jQuery 也复制该输入上的数据和事件。

克隆文档

于 2013-10-28T01:49:47.310 回答