我有一个对象,其中包含一些数据,我希望在单击复选框时访问这些数据。
以下是我拥有的复选框的示例。
<input type="checkbox" id="dealership1" name="dealership1">
<input type="checkbox" id="dealership2" name="dealership2">
<input type="checkbox" id="dealership3" name="dealership3">
<input type="checkbox" id="state1" name="state1">
<input type="checkbox" id="state2" name="state2">
<input type="checkbox" id="state3" name="state3">
因此,当我单击复选框时,我想访问相应的对象并将“名称”和“图像”分配给变量,以便稍后将它们添加到我的页面中。我会通过执行类似 var foo = docs.dealership.dealership1.name 的操作来做到这一点,但我遇到了问题,因为我读到我不能使用 docs.var1.var2.name 这样的变量
var docs = {
'dealership': {
dealership1: {
"name" : "Trade-In Appraisal",
"image": "http://unsplash.it/100"
},
dealership2: {
"name" : "Service Details",
"image": "http://unsplash.it/200"
},
dealership3: {
"name" : "Referral Form",
"image": "http://unsplash.it/300"
},
},
'state': {
state1: {
"name" : "Application for Title",
"image": "http://unsplash.it/400"
},
state2: {
"name" : "Bill of Sale",
"image": "http://unsplash.it/500"
},
state3: {
"name" : "County of Title Issuance",
"image": "http://unsplash.it/600"
},
}
}
最佳答案
<input type="checkbox" data-id="dealership" name="dealership1">
<input type="checkbox" data-id="dealership" name="dealership2">
<input type="checkbox" data-id="dealership" name="dealership3">
<input type="checkbox" data-id="state" name="state1">
<input type="checkbox" data-id="state" name="state2">
<input type="checkbox" data-id="state" name="state3">
$('input').change(function() {
var type = $(this).attr('data-id');
var name = $(this).attr('name');
var n = docs[type][name].name;
});
关于javascript - 如何绑定(bind)复选框以从 javascript 对象获取正确的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924811/