的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为什么你不首先使用库? :)
伊沃首先回答,但也谢谢你! – Christophe 2010-12-03 04:47:08
感谢盒这一个作品! – Marin 2011-11-02 18:14:13