Jump to content

element.onclick="func()"


Drycodez

Recommended Posts

Why is it that each time i try to assign onclick attribute to an element through js, it will'nt work? E.g:

element.onclick="func()"

why is it that the above code ll not assign the attribute to the element? I have tried it several times, but still cant get it.

Link to comment
Share on other sites

why is it that the above code ll not assign the attribute to the element?
Because the syntax is wrong. Event handlers require their value to be a function. If the function takes no parameters, you just use the function name without parenthesis. For example,
function showMsg() {   alert("A message");}.....elem.onclick = showMsg;

However, if the function does require parameters, you must use what is called an anonymous function. It is sometimes also referred to as a lambda function. Basically, it is just a function without a name. For example,

function showMsg(msg) {   alert(msg);}.....elem.onclick = function() { showMsg("A message"); }

Link to comment
Share on other sites

Because the syntax is wrong. Event handlers require their value to be a function. If the function takes no parameters, you just use the function name without parenthesis. For example,
function showMsg() {   alert("A message");}.....elem.onclick = showMsg;

However, if the function does require parameters, you must use what is called an anonymous function. It is sometimes also referred to as a...

yeah, i got it! Thank!!!
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...