令牌输入的重复消除javascript代码
有许多文本框Django CharField,我使用tokenInput作为自动完成功能的JS插件。要初始化它们中的每一个,我需要使用不同的标记值设置prepopulate。我希望避免以下代码重复,如下所示令牌输入的重复消除javascript代码,javascript,django,code-duplication,jquery-tokeninput,Javascript,Django,Code Duplication,Jquery Tokeninput,有许多文本框Django CharField,我使用tokenInput作为自动完成功能的JS插件。要初始化它们中的每一个,我需要使用不同的标记值设置prepopulate。我希望避免以下代码重复,如下所示 $("#id_tags_1").tokenInput("/xyz/tag_search/", { theme: "facebook", onAdd: function(item){ tag_ids.push(item.id); $("#id_t
$("#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],
});
我遇到了另一篇SO帖子,其中建议使用类似[^id\u tags\]的正则表达式,但我不知道如何选择对应于不同标记的每个标记值。我想部分问题是我不知道如何访问标签id,否则我可能会将其拆分并提取号码。如果有任何其他优雅的解决方案,请提出建议。好的,您可以使用$[id^=id\u tags\uu]an选择它们。在回调中,如果插件类似于标准插件,那么它将引用引发导致回调的原始事件的元素。同样,如果插件在回调中以正常方式运行,那么this.id应该是发生事件的元素的id。但我不知道那个插件,有时候插件以不同的方式传递信息 如果该插件不提供对发生原始事件的元素的访问,您仍然可以使用each并使用each迭代器函数创建的闭包来记住id,从而消除代码的重复:
在这种情况下,我们为每个迭代器函数中的每个元素创建新的tagInput回调,这些回调是对迭代器函数调用的闭包,因此它们可以访问特定于每个调用的id局部变量,从而访问每个元素。如果术语闭包看起来有点陌生,不要担心,.$id\u tags\u 1,id\u tags\u 2,….令牌输入?预填充:tags_val[parseIntid.replace/^\D+/g,-1],@Kaiser:LOL,我刚刚意识到OP使用的是基于id的基于0的索引,经过编辑…代码非常相似:-
$("[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)
});
});