简体   繁体   中英

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. 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. 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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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