views:

867

answers:

1

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.

+5  A: 

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;
    });
});
tj111
Hey I learned something!
Mike Robinson
What is temp in this case?
Amir
Sorry, I pasted that in on accident. The callback function gets passed two parameters, the array key and the array item. So `this` and `element` are pointing to the same thing in this case. Hope that helps.
tj111
And I think he means .each() instead of .map()http://docs.jquery.com/Utilities/jQuery.map
Georg
Map() is a good idea, but if you want to use chaining as I do in my code, you must "return this" from the map function. So in the end, the code is the same length, but a little less efficient since we are now doing map() on the original array. (not that I care)
Amir