Home > front end >  How do i add parameter passing to this
How do i add parameter passing to this

Time:09-23

I need to add parameter passing to this code but don't know how, i tried a few different things but it just broke the code everytime

My code

CodePudding user response:

If you need to pass parameters to your calc function, you can just create an anonymous function from the click event, add some code to gather your parameters to pass in and then call the calc function like so:

document.getElementById("currencybtn").addEventListener('click', function () {
  let myParameter = 10;
  calc(myParameter);
});

And then in your calc function, you can name that parameter anything you'd like. It doesn't have to be named myParameter because your calc function will use the first variable you pass to it with the first variable you put inside of the parenthesis when you call your calc function:

function calc(param1) {
//param1 is myParameter from above
//JavaScript pulls in variables based on the order they are received
return param1   3;
}

CodePudding user response:

You can fetch the arguments from the target attribute of the event, somehing like this:

const button = document.querySelector('button');
button.addEventListener('click', calc, false);
button.randomParam = 'just a random parameter';

function calc(e)
{
  window.alert(e.currentTarget.randomParam);
}
<button class="input">click me</button>

  • Related