1

For a button, I need to set the function this calls, and the value used in that call, at runtime. I can do this like so:

var myfunction = /* ... */
var myvalue = /* ... */
button.setAttribute ("onclick", myfunction + "('" + myvalue + "')");

If I try instead:

button.setAttribute ("onclick", function () { myfunction(myvalue));

Firebug gives me a

"function statement requires a name"

even though, as far as I'm aware, I'm using a function expression here.

hugomg
  • 68,213
  • 24
  • 160
  • 246
gzost
  • 2,375
  • 1
  • 18
  • 25

3 Answers3

4
button.onclick = function() {
    myfunction(myvalue);
}

Using the proper event registration method would be better though:

button.addEventListener('click', function() {
    myfunction(myvalue);
}, false);
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

You're missing a closing brace.

button.setAttribute ("onclick", function () { myfunction(myvalue));

should be

button.setAttribute ("onclick", function () { myfunction(myvalue); });

But you probably don't want to use setAttribute to set the onclick of a button, try button.onclick = function () { myfunction(myvalue); }; instead

evan
  • 4,239
  • 1
  • 18
  • 18
0

If you are considering pure JavaScript:

function attachEvent(element, event, handler)
{
    if (element && element.attachEvent) {
        element.attachEvent("on" + event, handler);
    }
    else if (element && element.addEventListener) {
        element.addEventListener(event, handler, false);
    }
}

USAGE:

attachEvent(button, "click", myFunction);

Please be noted, IE requires attachEvent and addEventListener doesn't work on IE and works on other browser. So you have to consider both of these functions to make it cross-browser support.

Abdul Munim
  • 18,869
  • 8
  • 52
  • 61