如何使用jquery中的data属性访问json obj

时间:2014-05-21 06:08:17

标签: javascript jquery json

我有几个元素的数据属性。我只想使用jquery中的data属性访问JSON obj。

<div class="content">
   <div class="plans" data-plan="state-1"><span class="pricing-symbol">$</span>20</div>
   <div class="plans" data-plan="state-2"><span class="pricing-symbol">$</span>30</div>
   <div class="plans" data-plan="state-3"><span class="pricing-symbol">$</span>40</div>
   <div class="plans" data-plan="state-4"><span class="pricing-symbol">$</span>50</div>
</div>

JSON:

var pricing_list = {
    "US":{
        "symbol":"$",
        "state_1" : 20,
        "state_2" : 20,
        "state_3" : 20,
        "state_4" : 23

    },
    "BRL":{
        "symbol":"R$",
        "state_1" : 210,
        "state_2" : 220,
        "state_3" : 203,
        "state_4" : 123
    },
    "EU" : {
        "symbol":"€",
        "state_1" : 210,
        "state_2" : 20,
        "state_3" : 23,
        "state_4" : 123
    }
   }

function getCountry(obj){
    if (typeof google !== 'undefined' && google.loader.ClientLocation){
        var currentLocation = google.loader.ClientLocation.address.country_code;
        return (currentLocation in obj) ? currentLocation : 'US';
    }

    return 'US';
}
    var cur_country = pricing_list[getCountry(pricing_list)];

    $(".pricing-symbol").html(cur_country["symbol"]);

    console.log('.plans');

现在我得到了所有元素的货币符号。现在动态地,我想使用data-attribute实现定价。请帮助我....

1 个答案:

答案 0 :(得分:0)

尝试,

 var cur_country = pricing_list[getCountry(pricing_list)];
 $(".pricing-symbol").html(cur_country["symbol"]);

$('.plans').each(function () {
    var nodes = $(this).contents();
    nodes[nodes.length - 1].nodeValue = cur_country[$(this).data('plan').replace('-', '_')]
});

DEMO