如何根据单击对象的id调整变量

How to adjust a variable based on the id of the object that is clicked?

本文关键字:id 调整 变量 对象 何根 单击      更新时间:2023-09-26

我正在为我的HTML游戏制作一个商店系统,我想制作它,这样当你点击一个项目时,它就会获得id,并将该项目的变量降低1。

if(e.shiftKey && inShop[this.id] === 0) {
    coins = coins+price[this.id]
    coinUpdate();
    [this.id]--;    
}
var fish1 = 1
<html>
    <img class="item cookable" id="fish1" src="source">
</html> 

例如,当我点击一条鱼时,我希望它降低你库存中有多少条鱼的变量。因此,我需要更改一个同名变量中的[this.id]

不要使用window方法。它仅适用于global变量。

全局变量被定义为some_var = 10;,而不是var some_var = 10;。如果你是桌面编程背景,你会发现JS中的全局变量很尴尬。

相反,使用名称空间或对象(此方法)。

这样定义你的库存:

var inventory = {
    goldfish: 10,
    seahorse: 10,
    jellyfish: 10
}

对于HTML,ID方法是可以的,但为什么不使用data属性呢?它是用来保存元数据的,非常适合这种场景。

<img src="//placehold.it/32x32" class="item cookable" data-type="fish">

jQuery通过.data方法内置了对此的访问权限,因此当您需要根据单击的内容来减少或增加数量时,只需在必要时使用以下内容:

// Fetch the "type" of fish from the data attribute
var type = $(this).data("type");
// And update the inventory
inventory[type]--;

data属性用于其他元数据,因此data-foo="hello" data-bar="world"

这些可以使用jQuery .data()作为对象获取,它将返回{foo: "hello", bar: "world"} or fetch them individually by passing the data name.data("foo")`

就我个人而言,我会使用这个来代替ID。

[this.id]--不起作用。这将生成一个具有单个元素(this.id引用的字符串)的数组,并尝试递减该数组。递减数组没有多大意义。

不能像这样动态地访问局部变量(在某些情况下可以,但实际上不应该)。但是,可以用属性来实现,所以您必须稍微调整一下。

把你所有的东西都存储在一个对象中,也许可以称之为inventory

var inventory = {
    fish1: 10,
    fish2: 5,
    worms: 3
};

现在你只需要稍微调整一下就可以使用递减法:

if(e.shiftKey && inShop[this.id] === 0) {
    coins = coins+price[this.id]
    coinUpdate();
    inventory[this.id]--; // decrement an item count in your inventory
}

JS中的所有全局变量都是在窗口对象上创建的。如果每个id有一个变量,那么只需要执行window[this.id]--window[this.id]++。无论如何,在JavaScript中,Window对象充当全局名称空间,通常用变量混淆全局名称空间是不好的做法。您应该创建一个包含所有项目计数器的新对象(例如items),对于添加的每个项目,您可以在删除时执行items[this.id]++items[this.id]--