简体   繁体   English

如何调用嵌套在 forEach 循环中的 Javascript 函数

[英]How to call a Javascript Function which is nested inside a forEach loop

I'm trying to modify a plugin for adding input tags which is available here我正在尝试修改用于添加输入标签的插件,该插件可在此处获得

I've written a dumbed down version of my issue below.我在下面写了我的问题的简化版本。 The pluggin searches the page for any HTML with the class 'tags-input' and creates a bunch of functions for each one found to add and remove tags.该插件在页面上搜索任何带有“tags-input”类的 HTML,并为每个找到的添加和删除标签的函数创建一堆函数。 The pluggin triggers the addTag() function whenever a keydown event is detected.只要检测到 keydown 事件,插件就会触发 addTag() 函数。

[].forEach.call(document.getElementsByClassName('tags-input'), function (el) {
  function addTag(str){
    //code here adds a tag with a certain string "str"
  }
});

addTag("some string"); //function not found!

I want to be able to call the addTag() function from outside the forEach loop when a link from a live search is selected. I want to be able to call the addTag() function from outside the forEach loop when a link from a live search is selected.

I've tried adding listeners within the loop, however, since the links from the live search are generated from a database after the page loads the listeners don't appear to pick them up.我已经尝试在循环中添加侦听器,但是,由于来自实时搜索的链接是在页面加载后从数据库生成的,因此侦听器似乎没有选择它们。

How can I call the addTag() function from my live search?如何从实时搜索中调用 addTag() 函数?

Similar questions did not help with this specific issue:类似的问题对这个特定问题没有帮助:

Call javascript inside foreach loop - No Answer Given 在 foreach 循环中调用 javascript - 没有给出答案

call javascript function outside foreach loop - Different issue as far as I can tell 在 foreach 循环外调用 javascript 函数- 据我所知,不同的问题

Something Like This, No?这样的事情,不是吗?

I understand what you're trying to do: But to make this simple I've used a List of String Values just to represent another possible approach:我理解你想要做什么:但为了简单起见,我使用了一个字符串值列表来表示另一种可能的方法:

 // Why not create a list of functions which correspond to each list item? var doSomeThingFuncList = []; ["Yes","No","Maybe"].forEach(function (item) { // Assuming that we will create a function for each list item that must be called outside of the loop doSomeThingFuncList.push( () => { alert("Do Something"); } ); }); // The functions we have defined inside the for-loop can now be called from outside the forEach loop through indexing the function list defined at the beginning doSomeThingFuncList[0]();

Basically, knowing what function to run what index of the array you'd be able to callback these functions through events on those buttons.基本上,知道什么函数运行数组的什么索引,您就可以通过这些按钮上的事件回调这些函数。 But I am not sure what the scenario is behind this.但我不确定这背后的场景是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM