Cofey
Cofey

Reputation: 11404

How to get data from an object using jQuery?

I am using an object to store data. How can I get the data for the active person, then when a link is clicked, get it for the person who's link has been clicked?

HTML

<div id="people">
  <a href="#steve" class="active">Steve</a>
  <a href="#mike">Mike</a>
  <a href="#cindy">Cindy</a>
</div>

JavaScript

var $people = $('#people').find('a'),
    activePerson = $people.hasClass('active'),
    people = {
        steve: [{
            color: 'blue',
            pet: 'bird'
        }],
        mike: [{
            color: 'maroon',
            pet: 'dog'
        }],
        cindy: [{
            color: 'pink',
            pet: 'snake'
        }]
     };

console.log(people.activePerson);

$people.click(function (e) {
    e.preventDefault();

    activePerson = $(this).attr('href').slice(1);

    console.log(people.activePerson);
});

Upvotes: 0

Views: 49

Answers (1)

Kristian Barrett
Kristian Barrett

Reputation: 3742

You can select them in your array like this:

JSFIDDLE: http://jsfiddle.net/L5sHS/

var $people = $('#people').find('a'),
    activePerson = $people.hasClass('active'),
    people = {
        steve: [{
            color: 'blue',
            pet: 'bird'
        }],
        mike: [{
            color: 'maroon',
            pet: 'dog'
        }],
        cindy: [{
            color: 'pink',
            pet: 'snake'
        }]
     };

console.log(people.activePerson);

$people.click(function (e) {
    e.preventDefault();

    activePerson = $(this).attr('href').slice(1);

    console.log(people[activePerson][0].color);
});

In this example I print out the color of the clicked person.

Upvotes: 2

Related Questions