首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tokenInput的javascript代码去重复

tokenInput的javascript代码去重复
EN

Stack Overflow用户
提问于 2014-01-03 08:46:40
回答 1查看 154关注 0票数 0

有许多文本框(Django CharField),我使用tokenInput作为自动完成功能的JS插件。要使它们不合适,我需要使用不同的标记值来设置预填充。我希望避免如下所示的代码重复。

代码语言:javascript
复制
$("#id_tags_1").tokenInput("/xyz/tag_search/", {
    theme: "facebook",
    onAdd: function(item){
        tag_ids.push(item.id);
        $("#id_tag_domain").val(tag_ids.join(','));
    },
    onDelete: function(item){
        tag_ids = _.without(tag_ids, item.id);
        $("#id_tag_domain").val(tag_ids.join(','));
    },
    preventDuplicates: true,
    tokenLimit: 3,
    prePopulate: tags_val[0],
});
$("#id_tags_2").tokenInput("/xyz/tag_search/", {
    theme: "facebook",
    onAdd: function(item){
        tag_ids.push(item.id);
        $("#id_tag_domain").val(tag_ids.join(','));
    },
    onDelete: function(item){
        tag_ids = _.without(tag_ids, item.id);
        $("#id_tag_domain").val(tag_ids.join(','));
    },
    preventDuplicates: true,
    tokenLimit: 3,
    prePopulate: tags_val[1],
});

我遇到了另一个这样的帖子,其中建议使用像这个[^id_tags_]这样的正则表达式,但我不知道如何选择对应于不同标记的每个标记值。我认为问题的一部分是,我不知道如何访问标签id,否则我可以拆分它并提取数字。如果有任何其他优雅的解决方案,请建议。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-03 08:49:54

对,您可以使用$("[id^=id_tags_]") (一个属性-从选择器开始)来选择它们。在回调中,如果插件类似于标准插件,this将引用引发回调的原始事件所在的元素。因此(同样,如果该插件以正常方式运行),在回调中,this.id应该是事件发生的元素的id。但我不知道插件,有时插件以不同的方式传递信息。

如果该插件没有提供对发生原始事件的元素的访问,则仍然可以通过使用each和使用each迭代器函数创建的闭包来记住id来取消代码复制。

代码语言:javascript
复制
$("[id^=id_tags_]").each(function() {
    // Get the index from the element `id`.
    // Note: If your elements are always in *document* order, instead
    // of this next line, you could just accept `index` as an argument,
    // it'll be `0` for the first matching element, `1` for the next,
    // etc. But I'm not assuming the elements are in document order, so
    // I'm deriving the index from the `id`.
    var index = parseInt(this.id.replace(/\D/g, ''), 10) - 1;

    $(this).tokenInput("/xyz/tag_search/", {
        theme: "facebook",
        onAdd: function(item){
            tag_ids.push(item.id);
            $("#id_tag_domain").val(tag_ids.join(','));
        },
        onDelete: function(item){
            tag_ids = _.without(tag_ids, item.id);
            $("#id_tag_domain").val(tag_ids.join(','));
        },
        preventDuplicates: true,
        tokenLimit: 3,
        prePopulate: tags_val[index],   // <=== Use `index` here (I assume this is the place)
    });
});

在这种情况下,我们为tagInput迭代器函数中的每个元素创建新的each回调,它们是对迭代器函数调用的闭包,因此它们可以访问id局部变量(这将针对每个调用,因此也适用于每个元素)。如果“封闭”这个词看上去有点陌生,别担心,闭包并不复杂

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20899759

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档