简体   繁体   中英

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. The pluggin triggers the addTag() function whenever a keydown event is detected.

[].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'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?

Similar questions did not help with this specific issue:

Call javascript inside foreach loop - No Answer Given

call javascript function outside foreach loop - Different issue as far as I can tell

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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