如何绑定我的复选框以从javascript对象获取正确的数据?

时间:2017-05-11 20:17:20

标签: javascript jquery object checkbox

我有一个包含某些数据的对象,当我点击一个复选框时,我想访问它。

以下是我所拥有的复选框的示例。

  <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">

因此,当我点击一个复选框时,我想访问相应的对象并指定&#34; name&#34;和&#34;图像&#34;到变量,以便我以后可以将它们添加到我的页面。我会通过像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"
                },

            }

        }

1 个答案:

答案 0 :(得分:1)

<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;
    });