TheEvolvingMe TheEvolvingMe - 6 months ago 9
Javascript Question

Passing function while running a loop

I am starting off with html5 and not sure if I'm doing anything wrong in here.

What I'm trying to achieve is create a portfolio of items and when one is selected, pass the selected item to a function to process it.

I have put up a simple jsfiddle in here https://jsfiddle.net/rohannayak90/9u9rtf84/

data = JSON.parse('{"error":false,"items":[{"id":1,"name":"John"},{"id":2,"name":"Jordan"}]}');

jQuery.each(data.items, function(counter, item) {
//console.log(item);
h = '<a href="#" onclick="' + generateCallBack(item) + ';">' + item.name + '</a></br>';
$('#portfolio').append(h);
});

function generateCallBack(argItem) {
return function() {
itemSelected(argItem);
};
};

function itemSelected(argItem) {
//console.log(argItem.name);
alert(argItem.name);
};


Thanks in advance.

Answer

I would recommend to to create HTML using jQuery() and use .data(key, value) to store arbitrary value with element.

Additionally learn Event Delegation using .on() delegated-events approach, when generating elements dynamically.

General Syntax

$(staticParentContainer).on('event','selector',callback_function)

Snippet for your solution

$(function() {
  var data = JSON.parse('{"error":false,"items":[{"id":1,"name":"John"},{"id":2,"name":"Jordan"}]}');

  jQuery.each(data.items, function(counter, item) {
    //console.log(item);
    $('<a />', {
        href: '#',
        text: item.name,
        'class': 'myClass'
      })
      .data('item', item)
      .add('<br />')
      .appendTo('#portfolio');
  });

  $('#portfolio').on('click', 'a.myClass', function() {
    console.log($(this).data('item'));
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showcase" class="container">
  <ul id="portfolio" class="grid">

  </ul>
</div>

Comments