0

So I'm making a game, but I'm having trouble selling items. I made the object

var price = {
sword:3,
fish:1
}

And once you click on something with class "item", it should tell you the price Except It isn't working

$(".item").click(function(){
alert(price.(this.id))
});

Can someone help me?

Isha Dijcks
  • 74
  • 11

3 Answers3

6
$(".item").click(function(){
alert(price[this.id]);
});
Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
  • use like var price = {}; price.sword=3; price.fish=1; then use my solution – Rituraj ratan Aug 21 '13 at 12:53
  • 2
    There's no need to change the way the object is created. This is the correct solution for accessing a dynamically named property on an object, so there's another reason it's not working. Possibly due to the scope of the `price` object, or some other reason. – Anthony Grist Aug 21 '13 at 12:54
  • Yes, you are right, the .click function was placed wrong, it works now, thanks a lot! – Isha Dijcks Aug 21 '13 at 12:59
3

Replace

    alert(price.(this.id))

To

    alert(price[this.id])

You can't access object properties by dynamic names from dot notation, use subscript notation.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
1

access by

 alert(price[this.id]);