jQuery: inserting DOM elements and attaching events
<p>I'm working on a JQuery plugin and I am having a problem when creating DOM elements and attaching a click event to them.  My code for creating the DOM elements is shown below:</p>

<pre><code>    return this.each(function () {
        $this = $(this);

        $("&lt;div class=\"" + settings.headingClass + "\"&gt;" + $this.attr("title") + "&lt;/div&gt;").insertBefore($this).click(function () {
            alert($this.attr("title"));
        });
    });
</code></pre>

<p>The values of <code>$this.attr("title")</code> are correct when rendered on the page and the click event fires on each element however, the alert box always displays the value of <code>$this.attr("title")</code> for the last element.</p>

<p>Example:</p>

<p>My plugin is being applied to 3 elements with titles "Title1", "Title2" and "Title3".  The generated HTML displays these titles correctly but the alert box only displays "Title3" no matter what title element I click on.</p>

<p>Any ideas?</p>

<p><strong>Extra Information</strong></p>

<p>I'm providing some extra information to help with this.  I'm creating a basic expander plugin to try and get to grips with JQuery plugin development.</p>

<p>Example of HTML element:</p>

<pre><code>&lt;div class="MyExpander" title="Title1"&gt;
    This is my expanders content
&lt;/div&gt;
</code></pre>

<p>JS to create JQuery expander:</p>

<pre><code>$(".QuizExpander").expander({
    "headingClass": "ExpanderHeading"
});
</code></pre>

<p>Plugin code so far:</p>

<pre><code>(function ($) {
$.fn.expander = function (options) {
    var settings = {
        "headingClass": "",
    };

    if (options) {
        $.extend(settings, options);
    }

    return this.each(function () {
        $this = $(this);

        $("&lt;div class=\"" + settings.headingClass + "\"&gt;" + $this.attr("title") + "&lt;/div&gt;").insertBefore($this).click(function () {
            alert($this.attr("title"));
        });
    });
};
</code></pre>

<p>})(jQuery);</p>
