简体   繁体   English

jQuery单击与javascript对象关联的元素上的触发器

[英]jQuery click trigger on element associated with javascript object

I've got a section on my page where there's a couple of blocks. 我的页面上有一个部分,其中有几个块。 When loading this page, I create an array blocks[] that stores a block object for each one, these contain some more information on the blocks. 加载此页面时,我创建了一个数组块[],它为每个存储一个块对象,这些包含有关块的更多信息。

function block(info, DOM) {
    this.id = info["id"];
    this.DOM = DOM;
    this.title = info["title"];
    this.icon = info["icon"];
    this.author = info["author"];
}

The DOM field holds the with the object associated block. DOM字段保存与对象关联的块。 Now, I'm trying to figure out the best way to get hold of my block object when you click the block. 现在,我正在尝试找出在单击块时获取块对象的最佳方法。

$(".block").click(..)

I'm currently thinking of using the above ^ and then using the index of the clicked element to get the block object out of the blocks[] array, but I'm left wondering if there would be some way to link it more directly with the .DOM field in Block, like having a specific click trigger in the block class. 我正在考虑使用上面的^然后使用clicked元素的索引从块[]数组中获取块对象,但是我想知道是否有某种方法可以更直接地链接它阻止中的.DOM字段,就像在块类中具有特定的单击触发器一样。 Is there a cleaner way like that to do it or should I just use the index? 是否有更清洁的方式来做或者我应该只使用索引? Thanks in advance! 提前致谢!

Yes, that is Indeed a way of doing. 是的,这确实是一种做法。

However, instead of attaching event handlers for each block as shown below 但是,不要为每个块附加事件处理程序,如下所示

$(".block").click(function(e){
  // do event handling
});

you could try event delegation as shown below 您可以尝试事件委派 ,如下所示

you can use event delegation 你可以使用事件委托

var blocks=[{},{},{}];

$("parent_for_blocks").on('click', '.block', function(e){
  // do event handling
  var index = $(this).index();
  console.log(blocks[index]);  // returns clicked block information
});

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

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