simply because you are accessing an object in your first example and not a DOM object as in other, if their obejtos are global so you can access
alert(window[this.id].food);
or
alert(eval(this.id + ".food"));
Pregunta
I have a constructor which I then make the object library_science1 with:
function librarytech(humanity,food,wood,metal,wealth)
{
this.humanity=humanity;
this.food=food;
this.wood=wood;
this.metal=metal;
this.wealth=wealth;
}
var library_science1=new librarytech(0,200,200,0,0);
I have this as a click function:
$("[id^='library_']").click(function() {
var idd = this.id;
alert(idd);
});
where the html is simply
<span id='library_science1'></span>
The code above works fine, alerting 'library_science1' nicely... it even works when I use the alert to directly pull one of the objects properties.
$("[id^='library_']").click(function() {
alert(library_science1.food);
});
But I have many library_[SOMETHING] objects, corresponding each to there own
<span id="library_[SOMETHING]"></span>
line.
I'm trying to pull the objects properties depending on which one is clicked. Such as:
$("[id^='library_']").click(function() {
alert(this.id.food);
});
or
$("[id^='library_']").click(function() {
var x = this.id;
alert(x.food);
});
The end purpose being that I can ultimately do things like:
foodamount -= this.id.food
Why isn't this working :/ :(
Solución
simply because you are accessing an object in your first example and not a DOM object as in other, if their obejtos are global so you can access
alert(window[this.id].food);
or
alert(eval(this.id + ".food"));
Otros consejos
I made a test here using eval() and this works:
$("[id^='library_']").click(function() {
alert(eval(this.id).food);
});
$("[id^='library_']").click(function() {
var x = eval(this.id);
alert(x.food);
});