eriq
eriq

Reputation: 1564

JQuery adding elements including a remove listener

What is the best way to add elements, incl. a link to remove themselves, to a div? This almost works:

function displayElements(objekt) {
    $('#container').empty();
    for(var key in objekt) {
        if(objekt.hasOwnProperty(key)) {
            $('#container').append('<div id="' + key + '">' + 
                key +
                '<a id="del' + key + '">delete'</a></div>');
            $('#del' + key).click(function() {
                delete objekt[key];
                displayElements(objekt);
            });
        }
    }
}

The strange effect is, that no matter which delete link I click, always the last element gets deleted. Why is that and is there a more elegant way to accomplish this?

Regards, Eriq

Upvotes: 2

Views: 265

Answers (2)

karim79
karim79

Reputation: 342635

You can replace that with:

// build your markup
function displayElements(objekt) {
    var container = $('#container').empty();
    for (var key in objekt) {
        if (objekt.hasOwnProperty(key)) {
            container.append('<div id="' + key + '">' + key + '<a id="del' + key + '">delete< /a></div > ');
        }
    }
}


displayElements(objekt);

// bind to all anchors who's ids start with 'del'
$("#container").on("click", "a[id^='del']", function() {
    $(this).remove();
});

Upvotes: 1

Blender
Blender

Reputation: 298106

I'd move the event stuff out of the loop:

function displayElements(objekt) {
  $('#container').empty();

  for (var key in objekt) {
    if (objekt.hasOwnProperty(key)) {
      var $div = $('<div />');
      $div.prop('class', 'delete');
      $div.append($('<a />').attr('id', 'del' + key).text('delete'));
    }
  }
}

$('.delete').on('click', 'a[id^="del"]', function() {
  // Delete your stuff
});

Upvotes: 0

Related Questions