Reputation: 4438
I am creating a popup menu with jQuery with some buttons. Number of buttons is flexibel. For each item in the variable 'items' there is one button. The problem: If the button is clicked I want to know to which item it belongs to.
In other programming languages there is a so called 'tag'-field where you can put an integer or an object for identification. What is the best way in jQuery?
var popup = $('<div />');
for (var i = 0; i < items.length; i++)
{
var btn = $('<div>' + items.Name + '</div>').appendTo(popup).button().click(
function(e) {
// alert($(e.target).tag);
popup.hide();
}
);
// btn.tag = i;
}
Upvotes: 2
Views: 188
Reputation: 7280
Try looking at .data()
. This will allow you to store information associated with a key
for any element.
var popup = $('<div />');
for (var i = 0; i < items.length; i++)
{
var btn = $('<div>' + items.Name + '</div>').appendTo(popup).button().click(
function(e) {
// alert($(e.target).tag);
popup.hide();
}
);
btn.data("index", i);
}
You can the retrieve the information using btn.data("index")
where btn
is a jQuery object containing the element.
The this
keyword will refer to the html element that has been clicked. You could alert the stored data using:
function(e){
alert($(this).data("index"));
}
Upvotes: 2
Reputation: 2997
You can use the "data-" attribute...
var popup = $('<div />');
for (var i = 0; i < items.length; i++)
{
var btn = $('<div ' + 'data-tag="' + i + '">' + items.Name + '</div>').appendTo(popup).button().click(
function(e) {
// alert($(e.target).tag);
alert($(this).data("tag"));
popup.hide();
}
);
// btn.tag = i;
}
Upvotes: 2