this
不会在函数内部工作,因为该函数是由对象调用的,window
因此this
将引用window
.
如果要将代码包装在一个函数中,则必须包装该函数,使用this
set 调用它或将其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,那么为什么不把一些东西放在一个“脚本”标签中呢?
更新
使用脚本块,您可以在其中声明您的函数,然后在 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 时,我仍然在问自己,为什么不首先使用库?:)