这是我第一次使用对象,因此我仍在学习JavaScript / jQuery。
当单击时,我有一个函数,将变量设置为单击的图像的类。我希望运行另一个函数,该函数根据先前的变量在对象中编辑一个值。我了解我要做的事情看起来像这样:
marri.selected = 1;
我遇到的问题是这样:
// in this case, let's say I clicked on one called 'marri'
character = $(".units a").attr("class");
// what I want this to read is 'marri.selected = 1' but as any name through the variable 'character'
character.selected = 1;
那么这有可能通过另一种方式吗?
答案 0 :(得分:3)
我假设您实际上可能有多个字符。因此,在单个对象中维护字符列表可能很有意义。每个角色的统计信息将是该对象的属性。这样一来,便可以按照您想象的方式动态引用相关属性。
因此,假设您有一个characters
对象,如下所示:
var characters = {
"marri": { selected: 0},
"someOtherCharacter": { selected: 0 }
}
您可以像编写时一样根据其类来获取该字符:
characterName = $(".units a").attr("class");
(或者,如果您要响应对该元素的单击,则实际上可能是characterName = $(this).attr("class");
。)
...,然后使用该character
值通过bracket notation来引用对象中的属性:
characters[characterName].selected = 1;
演示:
var characters = {
"marri": {
selected: 0
},
"someOtherCharacter": {
selected: 0
}
}
$(function() {
$(".units a").click(function(e) {
e.preventDefault();
characterName = $(this).attr("class"); //slightly different to the above example - this directly gets the class of the clicked link
characters[characterName].selected = 1;
console.log(characters); //just to show the object has been updated
});
});
.units a
{
padding: 5px;
border: 1px solid #cccccc;
margin: 1px;
}
.units a:hover
{
cursor:pointer;
background-color: #cccccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="units">
<a class="marri">Marri</a>
<a class="someOtherCharacter">Some Other Character</a>
</div>