我完全卡住的东西,可能是很基本的:布尔变量基于对象属性
我使用一个构造函数来创建一些游戏道具:
function itemCreator(itemName, itemType, itemPosition) {
this.itemName = itemName;
this.itemType = itemType;
this.itemPosition =itemPosition;
}
new itemCreator('shootUp001', 'item_up', 108);
new itemCreator('shootLeft001', 'item_left', 608);
new itemCreator('shootLeft002', 'item_left', 40);
后来我指定对于类似的商品图片:
function assignImages(item){
itemObject =item;
itemType = itemObject.itemType;
var itemDiv = document.getElementById(itemType); //get the div that has the name of this item
itemDiv.innerHTML = '<img src="' +itemType +'.png"/><span class="x">x</span><span id="' +itemType +'SpanCount"></span>' //put the picture of this item in there and also a span for the counting
}
这里就是我坚持:
我怎么能CREA te是我第一次插入某个itemType的图像时设置为“true”的布尔变量吗?我需要这个来避免两次插入相同类型的图像。
我知道我可以做一个简单的dom查找,但我试图学习JavaScript,并想了解如何能够避免在这种情况下。
那么当assignImage传递一个匹配itemType的对象时,基于itemType创建变量并修改该变量的智能方法是什么?
我没有看到你实际修改'items'的地方? – Pavlo
@Pavlo在Item类的第5行 - 我将项目实例分配给item中的itemType。 – megawac
以下是问题所在:如果我正确读取了代码,则只有在具有相同itemType的项目不存在时才会创建属性。但是我需要所有的项目,不管它们是否具有相同的itemType。我只需要为每个itemType分配一次图像。 –