javascript - Inline event handlers and anonymous functions -
i have need dynamically include , run script in page. using image onload event this:
<img src="blank.gif" onload="doit" /> the doit function looks (just made example):
this.onload=' ';this.src='image.jpg'; i have no control on page (i control html string page call), need include doit function explicitly in markup.
i tried using anonymous function, didn't work:
<img src="blank.gif" onload="function(){this.onload=' ';this.src='image.jpg';}" /> should write script inline, this:
<img src="blank.gif" onload="this.onload=' ';this.src='image.jpg';" /> and in case there limitations (e.g. script length)?
thanks help!
the this won't work inside function since function called window object, therefore this refer window.
if want wrap code inside function must wrap function, call this set element or pass this parameter:
<html> <body> <!-- call function , set accordingly--> <img src="foo.png" onload="(function(){...}).call(this)" /> <!-- pass parameter --> <img src="foo.png" onload="(function(e){....})(this)" /> </body> </html> yet doesn't make sense me:
i have no control on page (i control html string page call),
do have control on img tags? if can output abritary html, why not put in `script' tag?
update
script block declare function in there , call in onload event.
<script> function doit(el) { // code in here console.log(el.id); // stuff depending on id } </script> <img id="img1" src="foo.png" onload="doit(this)" /> <img id="img2" src="foo.png" onload="doit(this)" /> now need 1 function many images.
and if need fancy, can setup script tag pull in jquery or other library.
<script src="somepathtojquery"></script> <script> // jquery stuff in herep if need lot of these handlers jquery job.
still i'm asking self when have full control on html why don't use library in first place? :)
Comments
Post a Comment