JerryDeveloper
JerryDeveloper

Reputation: 139

jQuery read data from event

Here I have a problem:

I created one div and passed some data into it:

var div = $("<div />");
$.data(div, "a", 1);
div.on("click", function(event) {
    console.log($.data(event.target, "a")); // print undefined
});

It looks like I could not retrieve data bound with an UI element this way. I would like to know why and whether there is any alternative for this - get a piece of data associated with an UI element within an event.

Thanks!

Upvotes: 1

Views: 141

Answers (1)

gentiane
gentiane

Reputation: 6845

Try this ;-)

var div = $("<div>clic</div>").appendTo('body');
div.data("a", 1);
div.on("click", function() {
    console.log($(this).data("a"));
});

JsFiddle : http://jsfiddle.net/t3n8y2xz/

Upvotes: 3

Related Questions