2010-12-03 67 views
3

我需要在页面中动态包含并运行脚本。我使用的是图像的onload事件这样的:内联事件处理程序和匿名函数

<img src="blank.gif" onload="DoIt" /> 

的DOIT功能看起来像这样(只是由这个例子):

this.onload=' ';this.src='image.jpg'; 

我在页面本身没有控制(我只控制该页面将调用的HTML字符串),所以我需要在标记中明确包含DoIt函数。

我尝试使用匿名函数,但它没有工作:

<img src="blank.gif" onload="function(){this.onload=' ';this.src='image.jpg';}" /> 

如果我只是写剧本在线,就像这样:

<img src="blank.gif" onload="this.onload=' ';this.src='image.jpg';" /> 

而且在这种情况下,还有什么限制(如脚本长度)?

感谢您的帮助!

回答

14

this不会在函数内部工作,因为函数被window对象调用,因此this将参考window

如果你想换一个函数内部的代码,必须用该功能,与this集的元素调用或通过this作为参数:

<html> 
    <body> 
     <!-- call the function and set the this accordingly--> 
     <img src="foo.png" onload="(function(){...}).call(this)" /> 

     <!-- pass the this as a parameter --> 
     <img src="foo.png" onload="(function(e){....})(this)" /> 
    </body> 
</html> 

然而,这并没有真正的道理给我:

我在页面本身没有控制(我只控制HTML字符串,该页面会调用),

你只能控制img标签吗?如果你可以输出abritary HTML,那么为什么不把一些东西放在`script'标签中呢?

更新
有了一个脚本块,你可以声明你的函数在那里,然后简单地调用它的onload事件。

<script> 
    function doIt(el) { 
     // code in here 
     console.log(el.id); // you could do stuff depending on the id 
    } 
</script> 

<img id="img1" src="foo.png" onload="doIt(this)" /> 
<img id="img2" src="foo.png" onload="doIt(this)" /> 

现在,你只需要一个功能的许多图像。

如果你需要真的很喜欢,你可以设置你的脚本标签来拉入jQuery或任何其他库。

<script src="somepathtojquery"></script> 
<script> 
    // do jquery stuff in herep 

如果您需要很多这些处理程序jQuery可以完成这项工作。

仍然我问自己,当你完全控制HTML为什么你不首先使用库? :)

6

尝试:

<img src="blank.gif" onload="(function(el){el.onload=' ';el.src='image.jpg';})(this)" /> 
+0

伊沃首先回答,但也谢谢你! – Christophe 2010-12-03 04:47:08

+0

感谢盒这一个作品! – Marin 2011-11-02 18:14:13

相关问题