views:

68

answers:

3
var types = {
  "Grocery": "gro",
  "Restaurant": "res",
  "Bar": "bar",
  "Pizza Delivery": "piz",
  "Quick Service": "qui",
  "Retail": "ret",
  "Salon": "sal"
}

$(".type_changer").attr("id", types[$(this).text()]);

I understand that the class type_changer id is being changed to the part of this array but I don't understand types[$(this).text()]

and this line

$(this).parents('.select-holder').find('.text').text($(this).text());

seems almost understandable but I get confused on the .parents and the .find('.text').text($(this).text());

+1  A: 

$(this).text() will get the text inside the current DOM element and it will use this text to find the corresponding value in the array (for example types['Restaurant']).

Darin Dimitrov
+3  A: 

The $(this).text() takes the text of the current element (the <li> you're looping over in your case, unless your markup has changed).

It then uses that text as the key on the types object, basically doing types["Grocery"] when you click the "Grocery" link for example.

In JavaScript you can do types.Grocery or types["Grocery"] to access the property, which has a value of "gro".


The last statement is taking that same "Grocery" test and setting it as the text for the class="text" element in the parent.

Nick Craver
But won't that make all `.type_changer` elements have the same id, which is the corresponding value of the current element `.text()`? Because `this` is evaluated where it is called, not on every element: `$(".type_changer").attr("id", types[$(this).text()]);`
aularon
@aularon - There's a bit of context missing in the question, this happens inside a loop over the `<li>` elements :)
Nick Craver
If anyone's curious how to do this outside that loop though, then it would be: `$(".type_changer").attr("id", function() { return types[$(this).text()]; });`
Nick Craver
+1  A: 

On every element that has class 'type-changer', change it's ID to the value mapped in types to the text in the element, eg.

<div class="type-changer">Salon</div>

would be converted to

<div class="type-changer" id="sal">Salon</div>
axel_c