I'm working my way through the O'Reilly jQuery Cookbook. On p. 100 there is an example where I don't get one detail. I'm in my first week of looking at jQuery, so that's no surprise, but I'm hoping someone can clarify.
The function is a toggle with a few bells & whistles:
onValue
and offValue
are both Booleans, and must have opposite senses, and it might have been clearer to have only one of them, but the idea is to accommodate something where (for example) name
is "disable".
the optional on
, also a Boolean, lets caller use this as a "set" instead of a "toggle"
jQuery.fn.toggleAttr = function (name, onValue, offValue, on) {
function set($element, on) {
var value = on ? onValue : offValue;
return value == null ? $element.removeAttr(name) : $element.attr(name, value);
}
return on !== undefined ?
// next line is where I'm confused
set(this, on) :
this.each(function (i, element) {
var $element = $(element);
set($element, $element.attr(name) !== onValue);
});
};
How is set( this, on )
working here? It seems to be working on the list of elements, but something needs to happen to each element, and I don't see what would cause any iteration. I'd have expected something more like the on === undefined
case, something like:
this.each (function( i, element ) {
set( $(element), on);
)}
So, am I missing something?