0

I am able to set href properly like this:

var a = document.createElement("a");
a.setAttribute('href','doWork()');

However, I am clueless as to how do I do this when function needs a parameter:

var a = document.createElement("a");
a.setAttribute('href','doWork(money)';

#Using it like this, the url is doWork(money), but I need doWork(1), doWork(2)...
#I used a for loop, but doWork(i), when used with '' gives 'doWork(i)'.

#I have function doWork(money), with values of money ranging from 1 to 10.

How could I do that?

I have already tried this as per the links...mine is duplicate of.

for(var i=1; i<=10;i++){

 var link = 'doWork(i)'   #Sets link = doWork(i)
 var link = doWork(i);    #Nothing happens here

 a.setAttribute('href','doWork(i)';
ksalf
  • 37
  • 8
  • Where does the `money` variable come from? Couldn't you just call a function that retrieves that value? – Marc Mar 31 '19 at 14:44
  • @Marc: Sir, please see edits, the last block. My doWork(money) function needs values to operate, that's why I am sending values- money. – ksalf Mar 31 '19 at 15:03
  • `var link = 'doWork('+ i + ');'; a.setAttribute('href',link);` Can be done a little more cleanly with template strings, but I couldn't get the stackoverflow markup to escape backticks. – Marc Mar 31 '19 at 15:08
  • @Marc: Very nice, thanks a lot Sir. String concatenation it is, works nicely. – ksalf Mar 31 '19 at 15:20

1 Answers1

0

try like this.

var a = document.createElement("a");
a.setAttribute('href',`doWork(${money})`);
AlexZvl
  • 2,092
  • 4
  • 18
  • 32
  • 1
    Thank you sir, that works. But, why have you been downvoted, is it a bad way to use it like that? – ksalf Mar 31 '19 at 15:07
  • @ksalf I think just because it was answered already. – AlexZvl Mar 31 '19 at 15:09
  • No problem, I accepted the answer, however, the low rep that I am with, I just couldn't upvote. It would be very nice, if you explain it a bit, if you have time to do so. Thanks a lot ! – ksalf Mar 31 '19 at 15:12
  • if you want to use variables inside string , you need to wrap your string like this `this is string ${yourVariable}` – AlexZvl Mar 31 '19 at 15:15