【问题标题】:jQuery Cloned django-selectable Autocomplete Dropdowns Not WorkingjQuery克隆的django-selectable自动完成下拉菜单不起作用
【发布时间】:2013-11-05 21:25:25
【问题描述】:

正如标题所述,我的页面上有一个 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 的 cmets,我做了以下修改:

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');

【问题讨论】:

    标签: javascript jquery django autocomplete


    【解决方案1】:

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

    var acClone = autocompleteArray.clone(true);
    

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

    Clone documentation

    【讨论】:

    • 谢谢 SunnySydeUp。我已根据您的反馈对我的代码进行了修改。您走在正确的轨道上,但现在需要将事件绑定到克隆的下拉列表。我不知道该怎么做。
    • 在快速浏览了 django-selectable 的 javascript 源代码 (jquery.dj.selectable.js) 之后,它似乎在做 window.bindSelectables('body');。也许试试看?
    • 是的!只需稍作修改即可:您必须将 .clone() 的 deepcopy 标志设置为 false。有一个小错误(每个表单都有一个重复的下拉按钮,但自动完成和下拉功能在那里。非常感谢。我尝试了大约 20 种不同的东西,总体上试图让它工作。
    猜你喜欢
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2020-10-06
    相关资源
    最近更新 更多