0
for(let feature of features){
   $("#menuList").append("<li></li>");
}
$("#menuList li").on('click', function(ev){ 
  // I need a reference to the original feature object here 
});

What is the best way to get a reference to the original feature-object within the click handler (without passing some ID as a data tag and iterating over the list again)?

Ideally, I could do something like

for(let feature of features){
   $("#menuList").append("<li></li>").on('click', function(feature){ //do something with the feature object });
}

But this does not work.

netik
  • 1,736
  • 4
  • 22
  • 45
  • Did you try using $(document).on('click', "#menuList li", function(ev){ ... because your element is appended – Armin Feb 15 '17 at 12:58
  • What actually is `feature` or `features` here? Are you appending anything to `li` from it? – Guruprasad J Rao Feb 15 '17 at 13:01
  • feature is just an object. I will definitely use some of it's attributes to build the `li` but I really need to pass the object to the click handler, that's the problem – netik Feb 15 '17 at 13:02
  • 1
    Take a look here: http://stackoverflow.com/questions/2159368/jquery-append-return-appended-elements `$.appendTo` looks to be another function that will return a reference to the just appended element (not a ref to the parent element like `$.append()` does), and you'll be able to set that `.on('click'` directly, I suppose. – artur99 Feb 15 '17 at 13:03
  • Thanks artur99, this looks promising! Gonna try that. – netik Feb 15 '17 at 13:03
  • $(this) inside the click function would be the reference to the
  • you clicked. Why are most people giving a complicated answer to it while it's really simple lol.
  • – Sinan Samet Feb 15 '17 at 13:13
  • @SinanSamet, How can OP access `feature` object? `$(this)` is not a magic want will solve all problem. Seems you didn't understood the problem – Satpal Feb 15 '17 at 13:31