6

我需要在页面中动态包含和运行脚本。我为此使用了图像加载事件:

<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';" />

在这种情况下是否有任何限制(例如脚本长度)?

谢谢你的帮助!

4

2 回答 2

20

this不会在函数内部工作,因为该函数是由对象调用的,window因此this将引用window.

如果要将代码包装在一个函数中,则必须包装该函数,使用thisset 调用它或将其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 时,我仍然在问自己,为什么不首先使用库?:)

于 2010-12-03T03:30:30.807 回答
8

尝试:

<img src="blank.gif" onload="(function(el){el.onload=' ';el.src='image.jpg';})(this)" />
于 2010-12-03T03:28:26.833 回答