1

I have a variable ElementAction which is a string javascript:deleteRow();. How do I assign the literal content of ElementAction to an onclick handler of another HTML element. HTMLElement.onclick = ElementAction doesn't work.

Thanks for any help.

1
  • 1
    You can using eval, however I absolutely don't recommend running a string. Commented Feb 15, 2011 at 0:06

2 Answers 2

4

Get rid of that "javascript:" prefix first; it's useless. You can create a function instance from your string with:

var handler = new Function("event", ElementAction.replace(/^javascript:/, ''));

Then you can attach the handler either by setting the "onclick" attribute directly or by using one of the APIs as in JCOC611's answer.

Sign up to request clarification or add additional context in comments.

1 Comment

By the way I just realized that the "javascript:" prefix does work because it ends up acting as a label on the first statement of the function body :-)
1

You can:

element.onclick = deleteRow;

Or even more compatible:

if(element.attachEvent){
   element.attachEvent("onclick", deleteRow);
}else{
   element.addEventListener("click", deleteRow, false);
}

Running a string is not recommended.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.