Toni Au Toni Au - 1 year ago 50
jQuery Question

How to associate buttons with new objects (object nesting) in Javascript

So I need something similar to Facebook Messenger's gear button which can be seen only when a conversation box is hovered or is currently active (just to give an image to these words), but how can I associate the button to that object? The object nesting is really confusing me. This is what mine looks like right now.

table_data {

item_1: { fruits: [ {}, ..., {} ]},
item_2: { fruits: [ {}, ..., {} ]},
item_n: { fruits: [ {}, ..., {} ]},

is a
that has 3 buttons:

  1. Delete - deletes item and all content

  2. Options - opens popover options menu

  3. Expand - expands current
    to show
    array of objects

The user enters in a new
and then has the option to add objects to

document.getElementById("save").addEventListener("click", function() {
table_data[newItem] = { fruits:[] };
// helper function that appends HTML

So under options, user can "Add Fruits". How can I associate that "Add Fruits" to the correct item since the "Options" button is just appended HTML.

If it helps, the helper function looks like this.

function appendHTML(item) {
$("#list").append('<li class="enter"><div class="listContent"><a href="#" class="close"></a><span class="itemName">'+item+'</span></a><a href="#" id="expand"></a><a href="#" id="gear"></a></div></li>');


If anyone happens to need an answer to this in the future...

$(document).on('click', "#list > li > .listContent > .gear", function() {

Answer Source

This is a duplicate of this question. There, you will find multiple answers. I think the best would probably be storing the element in a var and then you can easily target it with whatever you want after you append it