-2

so if you have this html:

<li id='hi'></li>

and let's say this jquery:

var obj = {
    hi: {
        role:'something'
    },
    hello: {
       role: 'something'
   }
}


$('li').click(function(e) {
            var nameTrig = e.target.getAttribute('id');
            alert(obj.nameTrig.role);
});

I click the li => so if i call obj.nameTrig.role, it should be 'something'? I tried this and in the console it said: Uncaught TypeError: Cannot read property 'name' of undefined

Please help thanks

Pixeladed
  • 1,773
  • 5
  • 14
  • 26

2 Answers2

3

you need to use bracket notation as the member operator to access a property where the property key is stored in a variable

alert(obj[nameTrig].role);

Also you can use this.id to access the clicked li elements id, e.target.id will give wrong results if you have another element within the li and you click on it

$('li').click(function (e) {
    var nameTrig = this.id;
    alert(obj[nameTrig]role);
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

You will need the bracket notation style to accomplish this.

alert(obj[ nameTrig ].role);
jAndy
  • 231,737
  • 57
  • 305
  • 359