Given this piece of code, I don't understand the part I commented:
Code:
function attr(elem, name, value) { // {{{
if (!name || name.constructor != String) return '';
/* I don't understand the [name] = name, and the relation
* of [name] with the previous code in the line. */
name = {'for': 'htmlFor', 'class': 'className'}[name] = name; // I don't understand this line.
if (typeof value != 'undefined') {
elem[name] = value;
if (elem.setAttribute)
elem.setAttribute(attrName, attrValue);
}
return elem[name] || elem.getAttribute(name) || '';
} // }}}
I'll greatelly appreciate any clarification on that. A link with some doc related
to that is equally interesting. Thanks in a advance.
That line doesn't make sense to me as it is. From what it looks like they are trying to give you the correct attribute name for the name you are passing, eg:
"for" would translate to "htmlFor".
But for that to work properly the line would need to look like so:
Code:
name = {'for': 'htmlFor', 'class': 'className'}[name] || name;
It is from the book Pro Javascript Techniques, from John Resig. It is a function
that gets an attribute's value (or null) if two argumets are passed, and sets an
attribute's value if three arguments are passed. I tested it and works perfectly, but
I don't understand that line...
That line doesn't work properly as it is, right now it's creating an anonymous object, replacing a member with a value then returning the value you replaced it with, which is pointless. The correction I showed you previously fixes that bug:
Bookmarks