stiller_leser
stiller_leser

Reputation: 1572

Add data to dynamically created element and bind event

I'm trying to bind a click-event to a dynamically created element. Since I need to identify the exact element later after it was clicked, I'm trying to save attach an ID to it. Currently it looks like this:

var li = '<li class="item" data-type=' +$(this).attr("type")+' data-path="file://'+$(this).attr("path")+'" data-id="'+$(this).attr("id")+'">' + $(this).attr('name') + "</li>";
$(li).bind("click", {id : $(this).attr("data-id")}, function(event){
    console.log("ID: " + event.data.id);
});
$("#playlistfiles").append(li);

Unfortunately nothing happens if the element is clicked. I'm aware that this might be a duplicate, but after searching for awhile, I wasn't able to solve the problem.

Cheers, stiller_leser

Upvotes: 1

Views: 724

Answers (1)

Ram
Ram

Reputation: 144689

That's because you create a jQuery object but don't use it. You can use .appendTo() method.

$(li).bind("click", {id : $(this).attr("data-id")}, function(event){
    console.log("ID: " + event.data.id);
}).appendTo('#playlistfiles');

Or:

var $li = $(li).bind("click", {id : $(this).attr("data-id")}, function(event){
    console.log("ID: " + event.data.id);
});

$("#playlistfiles").append($li);

Why this happens?

li is a a string, by passing the string to the jQuery an unique object is created, $(li) returns a jQuery object, .bind() adds a handler and then like many other jQuery methods returns the current collection, the returned value is a jQuery object that actually is discarded since you don't store the retuned value and .append(li) only appends the original string not the created object.

Upvotes: 1

Related Questions