Explaining jQuery dialogs in the Nemikor Blog, Scott González uses the .each() method on an id selector:
$('#page-help').each(function() {
var dialog = $('<div></div>')
.load($(this).attr('href'))
.dialog( ... );
$(this).click(function() { ... });
});
Since an id selector can only return a single element, what is the purpose of using the .each() method? (which is normally for iterating over matched elements).
Is it just that there is no simpler way to execute a function for the 'page-help' element which provides access to $(this)?
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.
Select the ID's of different element and then use each() method to apply the CSS property on all selected ID's element. Then use css() method to set the background color to pink to all selected elements. Display the text which indicates the multiple ID selectors.
It lets you mess with something without polluting the surrounding namespace. An alternative might be:
(function($this) {
var dialog = $('<div></div>')
.load($this.attr('href'))
.dialog(...);
$this.click(function() { ... });
})($('#page-help'));
I don't know which of the two is more disturbing. And I suppose I don't really know that that was the reason for doing it that way (that is, namespace tidiness).
He's using a .each()
so this
refers to the element and his variables are encapsulated in that callback function, though this would also work (but you'd have the variables left around):
var $this = $('#page-help'),
dialog = $('<div></div>')
.load($this.attr('href'))
.dialog( ... );
$this.click(function() { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With