0

I have a function that creates a new <a> element and I want to add a onclick event to it, which is a function that increases the given value by 1.

In the function, I create these elements:

A number within spantags:

        var spantags = document.createElement("span");
        var anzahl = 1;
        spantags.innerHTML = anzahl;

And the mentioned <a> element:

        var plus = document.createElement("a");
        plus.innerHTML = "+";
        plus.onclick = more(spantags.innerHTML);

This, however, executed the function already in the function that creates this, so the number was increased to 2 on creation.

I read this answer on a similar question: https://stackoverflow.com/a/249084/1972372

This example worked, the alert only came up when the + was clicked on, but it is an inner function there, not a declared one like my "more(element)".

So my question is: Is it possible to set the onclick attribute to a declared function on a newly created element, like in my example, but prevent it from running immediately?

(The other article had a jQuery answer too, but unfortunately I have no knowledge about jQuery and cannot use it)

Community
  • 1
  • 1
Big_Chair
  • 2,781
  • 3
  • 31
  • 58

2 Answers2

3

Yes, just wrap it in a "proxy" function:

plus.onclick = function() {
    more(spantags.innerHTML);
};
landons
  • 9,502
  • 3
  • 33
  • 46
1

Sure, but first you have to understand that plus.onclick = more(spantags.innerHTML); will call more with the argument spantags.innerHTML and assign the result that is returned from that function call to plus.onclick.

You could wrap it in a proxy function as suggested previously, or you could take advantage of the bind method to bind the arguments to the function itself:

plus.onclick = more.bind(null, spantags.innerHTML);

Read up on Bind here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

ncthom91
  • 146
  • 6
  • This wouldn't actually have the same result. You'd be binding the current value of spantags.innerHTML ("1" at the time of binding), and will never increment past 2 – landons Jun 27 '13 at 16:35
  • It actually works with this, so I'll give this an upvote too, but I am confused about what the first parameter is. I read that it is the this argument, but I still don't really get it. I accepted the first answer because it was easier to understand. – Big_Chair Jun 27 '13 at 16:43
  • It's the "this" context. In the callback itself, using "this" will reference whatever you pass in as the first argument (in this case "null"). – landons Jun 27 '13 at 16:45