I'm trying to pull in data from our API with a data-
html trick.. I can call the data directly and it load just fine. But when i try to get the data variable from the data attribute it won't work.
Is there something flawed in my code?
ie
<span id="totalBalanceBTC" data-api-user-getbalance="totalBalance">--</span>
function dataAPI() {
let balanceUrl = 'https://api.example.io/v1/user/getbalance/username';
let balanceApiData = getApiData(balanceUrl);
$('[data-api-user-getbalance]').each(function (){
let dataUserBalance = $(this).data("api-user-getbalance");
let data = balanceApiData.dataUserBalance;
// WORKS
$(this).html(balanceApiData.totalBalance);
// DOES NOT WORK
$(this).html(balanceApiData.dataUserBalance);
});
}
1. jQuery's .data()
drops the data-
prefix and converts the remaining hyphenated string to camelCase , using the dashes as delimiters. It should be:
let dataUserBalance = $(this).data("apiUserGetbalance");
2. To access an object property using a variable, you'll need to use bracket notation . Otherwise you're trying to get the property "dataUserBalance"
, which doesn't exist.
let data = balanceApiData[dataUserBalance];
const balanceApiData = { totalBalance: 500 }; const $elem = $("#totalBalanceBTC"); let dataUserBalance = $elem.data("apiUserGetbalance"); let data = balanceApiData[dataUserBalance]; console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span id="totalBalanceBTC" data-api-user-getbalance="totalBalance"></span>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.