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.
From stackoverflow
-
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; }); });
Mike Robinson : Hey I learned something!Amir : What is temp in this case?tj111 : 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.Georg : And I think he means .each() instead of .map() http://docs.jquery.com/Utilities/jQuery.mapAmir : 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)
0 comments:
Post a Comment