Home > Net >  JavaScript call same function name multiple times
JavaScript call same function name multiple times

Time:10-22

I have a function and I want to call it multiple times the function generates a button but if I call it multiple times it won't have its own arguments. How I can do that I want every function to be unique?

function(); // I want this to call its own value
function(); // I want this to do something
function(); // I want this to call its own value
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Dont know if I really understand what you need, but the following example show you how to pass different arguments to the same function and call it many times you want.

let args = [{
  name: 'test',
  value: 'value1'
}, {
  name: 'test2',
  value: 'value2'
}, {
  name: 'test3',
  value: 'value3'
}];

function test(args) {
  if (args) //Check if function has arguments
  {
    let btn = document.createElement('button'); //create an element type button
    btn.innerText = args.name; //Set the created button text
    btn.value = args.value; //Set the created button value
    //Folowing code add 'EventListener' to catch the user 'click' action
    btn.addEventListener('click', function(e) {
      console.log('Button clicked with value: '   this.value) //Log the value of the clicked button to verify if our function is working (set the name and value of generated button)
    });
    document.body.appendChild(btn); //Append the created button to the DOM
  } else {
    //Eles do something else
    console.log('no arguments passed')
  }
};

test() //Function test executed w/o arguments

//Create a loop on args, just for the example
for (i = 0; i < args.length; i  )
  test(args[i]) //Funciton test() executed with arguments
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

One solution would be to use multiple functions. Make sure to give unique names to each of the functions.

function myFunction(){
  console.log('Hello World');
}

function mySecondFunction(){
  myFunction();
}

mySecondFunction();
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related