如何使用Prototype new Element()构造函数添加事件处理函数? [英] How to add event handler with Prototype new Element() constructor?

查看:206
本文介绍了如何使用Prototype new Element()构造函数添加事件处理函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用新的Element构造函数将img标签插入到我的文档中(像这样工作很好):

  $('placeholder')。insert(new Element(img,{id:'something',src:myImage}))

我想在加载这个图片时触发一个函数,但是我找不到正确的语法。我猜这是这样的(不起作用)。

  $('placeholder')。insert(new元素(img,
{id:'something',src:myImage,onload:function(){alert(MOO)}}))
pre>

我希望在同一行代码中执行此操作,而不必单独附加事件观察器。



编辑:元素创建时,需要注册事件,而不是之后。如果图像在事件被附加之前加载,事件将永远不会触发。在这种情况下,最好的解决方案是不使用Prototype或至少不是专有的。这样做:

  var img = new元素('img',{id:'logo',alt:'Hooray!' }); 
img.onload = function(){alert(this.alt); };
img.src ='logo.jpg';

关键是直接设置onload,而不是让Prototype的包装器为你做,并将src最后(实际上不确定这一点,但我最后确保安全)。



单线被高估。通过正确使用局部变量,上述内容同样适用。如果您必须拥有一行代码,请创建一个包装函数或破解Prototype核心,以确保正确分配(提交补丁!)。


I'm inserting an img tag into my document with the new Element constructor like this (this works just fine):

$('placeholder').insert(new Element("img", {id:'something', src:myImage}))

I would like to trigger a function when this image loads, but I can't figure out the correct syntax. I'm guess it's something like this (which doesn't work).

$('placeholder').insert(new Element("img", 
    {id:'something', src:myImage, onload:function(){alert("MOO")}}))

I'm hoping to do this in the same line of code and not to have to attach an event observer separately.

EDIT: The event needs to be registered when the element is created, not after. If the image loads before the event is attached, the event will never fire.

解决方案

In this case, the best solution is to not use Prototype or at least not exclusively. This works:

var img = new Element('img',{id:'logo',alt:'Hooray!'});
img.onload = function(){ alert(this.alt); };
img.src = 'logo.jpg';

The key is setting the onload directly instead of letting Prototype's wrapper do it for you, and set the src last (actually not sure about that, but I do it last to be safe).

One-liners are overrated. With proper use of local variables the above is just as good. If you must have a one-liner, create a wrapper function or hack the Prototype core to ensure proper assignment (submit a patch!).

这篇关于如何使用Prototype new Element()构造函数添加事件处理函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆