简体   繁体   中英

How to add jquery variable into span class attribute?

I'm trying to use Barfiller ( https://github.com/9bitStudios/barfiller ). Everything works, but I want to set the data-percentage value in the span class (now set as "50") to be dynamically filled via a JQuery variable.

HTML

<div id="bar1" class="barfiller">
    <span class="tip"></span>
    <span class="fill" data-percentage="50"></span>
</div>

Javascript

function onQuerySucceeded(data) {
    var projectstatus = data.d.projectstatus;
    $('#data-percentage').text(projectstatus);
}

Regards, Chris

$("#bar1 .fill").attr("data-percentage", projectstatus);

I changed your code to make it work.

You have to use $(...).data( key, value) to set a new value to a data-... field in JQuery .

In JS you woulr use .setAttribute("data-percentage", "50"); for example.

 $(document).ready( function () { console.log($(".fill").data('percentage')); onQuerySucceeded(40); console.log($(".fill").data('percentage')); }); function onQuerySucceeded(data) { var projectstatus = data; $('#bar1 [data-percentage]').data('percentage', projectstatus); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="bar1" class="barfiller"> <span class="tip"></span> <span class="fill" data-percentage="50"></span> </div> 

I have added a timeout of 2 seconds before executing onQuerySucceeded() function as I thought it might be handy for you in case, you are loading the new percentage after making an api (service) call. Hope it helps you:

 $(document).ready(function() { console.log('data percentage: ' + $(".fill").attr('data-percentage')); setTimeout(() => { // after 2 seconds var responseJson = {}; responseJson.d = { projectstatus: 15 }; onQuerySucceeded(responseJson); }, 2000); }); function onQuerySucceeded(data) { $('.fill').attr("data-percentage", data.d.projectstatus); console.log('data percentage: ' + $(".fill").attr('data-percentage')); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="bar1" class="barfiller"> <span class="tip"></span> <span class="fill" data-percentage="50"></span> </div> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM