简体   繁体   English

无法通过JavaScript添加事件侦听器

[英]Trouble adding event listeners via JavaScript

Currently I have a function which loops to create multiple HTML objects. 目前,我有一个循环创建多个HTML对象的函数。 Each time an object is created, I want to add an onClick function listener to that object so that I can trigger a function when each one is clicked. 每次创建一个对象时,我都希望向该对象添加一个onClick函数侦听器,以便在单击每个函数时可以触发一个函数。

What's the best way to do this? 最好的方法是什么?

Here's the code which creates my objects: 这是创建我的对象的代码:

    RenderMultipleChoice:function()
{
    this.c = paper.rect(this.x, this.y, this.shapeWidth, this.shapeHeight);
}

You might consider to use event delegation instead of adding a click listener to each created element. 您可能考虑使用事件委托,而不是向每个创建的元素添加点击侦听器。 Then you only have one event listener on a parent, and see what element the event bubbled from. 然后,您在父对象上只有一个事件侦听器,并查看事件起泡的元素。 It will also magically work for elements created in the future. 它还将神奇地用于将来创建的元素。

jQuery has two methods to handle this for you: jQuery有两种方法可以为您处理:

  • .live() - bind event listener to the body element (has disadvantages) .live() -将事件侦听器绑定到body元素(有缺点)
  • .delegate() - bind event listener to the (parent)elements you specify (better performance) .delegate() -将事件侦听器绑定到您指定的(父)元素(性能更好)

Example: 例:

$("#parent").delegate(".child", "click", RenderMultipleChoice);

live is an awesome function, but you should be aware of it's disadvantages: live是一个很棒的功能,但是您应该意识到它的缺点:

Performance difference between jQuery's .live('click', fn) and .click(fn) jQuery的.live('click',fn)和.click(fn)之间的性能差异

http://paulirish.com/2010/on-jquery-live/ http://paulirish.com/2010/on-jquery-live/

You can use addEventListener or attachEvent . 您可以使用addEventListenerattachEvent Assuming paper.rect returns a DOM element: 假设paper.rect返回一个DOM元素:

if(this.c.addEventListener)
{
  this.c.addEventListener("click", listenerFunction, false);
}
else 
{
  this.c.attachEvent("onclick", listenerFunction);
}

There are libraries to abstract this away. 有一些库可以将其抽象出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM