简体   繁体   English

单击“警告”对象属性

[英]'alert' an object property on click

I have a constructor which I then make the object library_science1 with: 我有一个构造函数,然后使用以下对象制作对象library_science1:

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 的HTML只是

<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. 上面的代码运行良好,很好地警告了“ library_science1” ...甚至当我使用警报直接拉出其中一个对象属性时,它也可以正常工作。

$("[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. 但是我有许多library_ [SOMETHING]对象,每个对象都对应于自己的<span id="library_[SOMETHING]"></span>行。

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 :/ :( 为什么这样不起作用:/ :(

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 仅仅是因为您在第一个示例中访问的是对象,而不是在其他示例中访问的DOM对象,如果它们的对象是全局的,则可以访问

alert(window[this.id].food);

or 要么

alert(eval(this.id + ".food"));

I made a test here using eval() and this works: 我在这里使用eval()进行了测试,并且可以正常工作:

$("[id^='library_']").click(function() {
            alert(eval(this.id).food);
});

$("[id^='library_']").click(function() {
    var x = eval(this.id);
            alert(x.food);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM