Reputation: 7
<div id="bach">Bach</div>
<div id="show">about composer</div>
$(window).load(function(){
bach = {"bdate": 1685, "bplace": "Eisenach, Germany"}
$("div").click(function(){
$("#show").text(this.id['bdate']); // This is the problem
});
});
Hi, I'm currently trying to create a way to dynamically access the bach object. If I use bach instead of this.id everything works fine. Somehow I need to find a way to convert this.id to something that I can use in the context of accessing a property in the bach object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators
Javascript: interpret string as object reference?
Here are a couple websites that my research led me to. Either I'm not understanding what they're saying or they are not exactly related to my problem.
Thanks
Upvotes: 1
Views: 39
Reputation: 318352
As you're clearly in the window scope, you can use bracket notation
$(window).load(function(){
bach = {"bdate": 1685, "bplace": "Eisenach, Germany"}
$("div").click(function(){
$("#show").text(window[this.id]['bdate']);
});
});
wether it's a good idea or not is another matter
or as suggested by Rocket Hazmat
var obj = { bach : {"bdate": 1685, "bplace": "Eisenach, Germany"}};
$(window).load(function(){
$("div").click(function(){
$("#show").text(obj[this.id]['bdate']);
});
});
Upvotes: 2