javascript - Setting the onclick event to a custom function results in syntax error -
given following example code want set onclick event function declare in same method (no function in global scope):
<html> <head> <title>title</title> </head> <body> <img id="img" class="std" src="http://www.free-animated-pictures.com/bug_crawls_on_screen.gif"/> <script type='text/javascript'> var = document.getelementbyid("img"); var func = function(){ var = document.getelementbyid("img"); if(i.classname === "std"){ i.classname = "hid"; i.style.display = "none"; } else if(i.classname === "hid"){ i.classname = "std"; i.style.display = "block"; } }; //func = func.tostring(); //func = func.replace("function ()", "") document.body.setattribute("onclick", func); </script> </body> </html>
if use code following error when event fired:
uncaught syntaxerror: unexpected token (
if instead take string of function , remove function part of it, script works expected:
func = func.tostring(); func = func.replace("function ()", "")
why so? there better way? can't declare function without function part, what's point in removing again?
you setting actual textual element's attribute string using setattribute
, in turn auto-wrapped in function!
also, if have worked, there no body click on once image had disappeared.
here working example you should not use, intended explain above statement:
here function func
converted string (and string expected, javascript calls .tostring()
method automatically, put in show happened).
then, prevent quoting problem (you used double-quotes in html , (in opinion, insane) reason browsers replace single quotes in javascript double quotes (and i've witnessed pre-compiling in browsers)), naively (because safe particular function) replaced double quotes single quotes.
still need remove function(){
, trailing }
.
arrived @ function string, can pass.
browser sets actual textual attribute , wraps code again inside function works.
<img id="img" class="std" src="http://www.free-animated-pictures.com/bug_crawls_on_screen.gif" /> intentional text filler, otherwise body shrinks 0*0 px leaving nothing click on... <script type='text/javascript'> var func = function(){ var = document.getelementbyid('img'); if(i.classname === 'std'){ i.classname = 'hid'; i.style.display = 'none'; } else if(i.classname === 'hid'){ i.classname = 'std'; i.style.display = 'block'; } }; document.body.setattribute( 'onclick' , func.tostring() .replace(/\"/g,'\'') .replace(/^function *\( *\) *{/,'') .replace(/} *$/,'') ); </script>
solution document.body.onclick=func
directly (as gillesc commented), or use document.body.addeventlistener('click',func,false)
(which confused with).
note backward compatibility (notably < ie9) you'd need attachevent
, here basic workaround:
function addeventhandler(elem, eventtype, handler) { if (elem.addeventlistener) elem.addeventlistener (eventtype,handler,false); else if (elem.attachevent) elem.attachevent ('on'+eventtype,handler); }
Comments
Post a Comment