Consider the javascript / jQuery code:
jQuery("<input/>").attr("type", "button").attr("value", "Click me")
.click(function()
{
alert("hello");
})
.appendTo(".someDiv");
This creates a button, binds an event handler to it and appends it to all elements with class "someDiv".
This works as expected ONLY if there is ONLY ONE element with class "someDiv" in the document. If there are more, the buttons are shown, but the click event is not fired.
I'm aware that I can use the following workaround:
jQuery(".someDiv").each(function()
{
jQuery("<input/>").attr("type", "button").attr("value", "Click me")
.click(function()
{
alert("hello");
})
.appendTo(this);
});
Which works, but is arguably less elegant.
I guess it has something to do with that in the first example there is only one element created and that same element is appended to all "someDiv"s, while in the second example there are actually multiple elements created, but I don't understand why that would mean that the event handler doesn't work in the first example.