Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaner (nested) closure in JavaScript with jQuery's each()

I was wondering if there is a cleaner (more succinct) way to do what each() is doing in following JavaScript code.

$(".moreinfodialog")
    .before('<a href="#">Click for more info.</a>')
    .each(function() {
        var temp = this;
        $(this).prev("a").click(function() {
            $(temp).dialog("open");
            return false;
        });
    })
    .dialog({ autoOpen: false, modal: true });

Note that the last call re-orders the dom elements, so .moreinfodialog classes are not next to the hrefs any more.

BTW: this source uses jquery/jquery-ui dialog to hide any text in a div with the .moreinfodialog class, and replace it with the Click for more info. text. When that text is clicked, a dialog with the text inside the original div is displayed.

like image 972
Amir Avatar asked Jan 16 '09 21:01

Amir


1 Answers

Edit: This answer was relevant in older versions of jQuery. In newer version $.map works differently.

Check out the $.map() function, used to perform the same operation on every element of an array.

$('.moreinfodialog').map(function(idx, element) {
    $(this).prev("a").click(function() {
            $(element).dialog("open");
            return false;
    });
});
like image 172
TJ L Avatar answered Oct 14 '22 07:10

TJ L