html - Set element onclick from JavaScript string -
i have code generates html this:
function foo(onclick:string):htmlelement { return parsehtml('<input type="button" onclick="' + escapehtml(onclick) + '" />'); }
which want migrate code this:
function foo(onclick:string):htmlelement { var input = document.createelement('input'); input.type = 'button'; input.onclick = onclick; // <= correct? return input; }
besides fact should using real javascript function instead of string of code, correct way set onclick
attribute using passed javascript string works same way did when generating html onclick
attribute?
edit:
the input.onclick
property code above setting supposed real javascript function object, not string of javascript (according mozilla docs) code above not correct.
i trying change implementation of foo()
without needing change usages. need able continue passing in string of javascript.
the solution turned out to convert javascript string function object single parameter using function
constructor:
function foo(onclick:string):htmlelement { var input = document.createelement('input'); input.type = 'button'; input.onclick = new function('event', onclick); return input; }
this gives passed javascript code exact same environment though written in onclick="..."
attribute in html:
- the
event
variable set appropriateevent
object - the
arguments
contain single argumentevent
object - the
this
object html element itself - the code run in it's own scope global scope next in scope chain
the solution comes http://perfectionkills.com/global-eval-what-are-the-options/
this work:
// ... input.onclick = (1,eval)('(function(event){' + onclick + '})'); // ...
Comments
Post a Comment