-1

I want to be able to create a <label> with a unique value, everytime a userclicks a button.

html

<button onclick="create()">test</button>

js

function create() {
  var on = "<label>1</label>"
  $(on).insertAfter("button");
}
Riz-waan
  • 603
  • 3
  • 13
  • 4
    No, don't do that. Create an array of anonymous functions, and call `test[2]()`. – Bergi Jun 16 '17 at 13:15
  • 3
    Please tell me: in what situation would that be useful? – PeterMader Jun 16 '17 at 13:16
  • Ain't that exactly what *function parameters* are for?! What's the difference between `test1()` and `test(1)`, except that the latter one makes sense? If you can dynamically create functions, then you can also simply dynamically evaluate the parameter inside the function. – deceze Jun 16 '17 at 13:20
  • 1
    I mean you could do `window["test" + i] = function()` but then you couldn't call `test2()` before that line as the function wouldn't be hoisted. But I agree with @Bergi don't do this :) – George Jun 16 '17 at 13:20
  • Please see my updates question. – Riz-waan Jun 16 '17 at 14:15
  • No, you don't solve the "infinite button" problem by creating new functions; wrong thinking. You just need one function that reacts to all buttons and you distinguish which button was pressed by passing parameters. – deceze Jun 16 '17 at 17:39
  • @deceze Could I please have an example of what you are saying? – Riz-waan Jun 16 '17 at 21:00
  • Please do not add meta messages to your titles. As you can see, even after this was reopened, there is a risk that redundant information is not updated. – halfer Jun 30 '17 at 21:25

1 Answers1

1

A better way would be storing your functions inside an array

let functions = [()=>console.log("func. 1"), ()=>console.log("func. 2")];

for(let i=0; i<functions.length; i++){
  functions[i]();
}
Weedoze
  • 13,683
  • 1
  • 33
  • 63