jQuery .click event binding to multiple dynamic elements
<p>Within my code I am trying to bind a click event to a dynamically created  element. Each element's click event has specific metadata used within the handler. Rather than appending dynamic attributes in HTML (there's a lot of them), I have an array of objects. This is also why I've not used a global event handler.</p>

<p>The code example may explain that better!</p>

<p>The problem I am having, is the click event is only called for the last created element. Here's some code:</p>

<pre><code>var MyObject = {
    additionalAttributes: { ... }

    getNode: function() {
        if (this.node) return this.node;
        var a = this.node = $(document.createElement("a"));

        // ... building the 'a' here.

        a.click(function(e) {
           e.preventDefault();
           alert(this.additionalAttributes.something);
        });
    }
}
</code></pre>

<p>Get Node is called like so:</p>

<pre><code>var x = new MyObject( ... );
$('#someDivElement').append(x.getNode());
</code></pre>

<p>This works nicely, but if I call the .append() with multiple instances of 'x', the click event is only fired for the last element added to the container.</p>

<p>Can anyone explain what I'm doing wrong here, or perhaps suggest a better approach to the overal problem?</p>

<p><strong>Edit:</strong> I didn't use a global binding (.on('click')) because of the additional functionality/data I need within handler. Having the .click() event defined in the way I did it provided access to the specific MyObject instance associated with that link.</p>

<p><strong>Edit 2:</strong> This code below would do what I am expecting, with each link having the callback, though for some reason my implementation does not do this:</p>

<pre><code>for (var i = 0; i &lt;= 10; i++) {
    $(document.createElement("a"))
        .attr("href","#")
        .text("Test Link " + i)
        .click(function() {
            alert("clicked");
        })
        .appendTo("div.test");
}
</code></pre>
