简体   繁体   English

如何将jquery变量添加到span类属性中?

[英]How to add jquery variable into span class attribute?

I'm trying to use Barfiller ( https://github.com/9bitStudios/barfiller ). 我正在尝试使用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. 一切正常,但我想在span类中设置数据百分比值(现在设置为“ 50”),以通过JQuery变量动态填充。

HTML HTML

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

Javascript 使用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 . 您必须使用$(...).data( key, value)JQuery中data-...字段设置新值。

In JS you woulr use .setAttribute("data-percentage", "50"); JS中,您将使用.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. 我在执行onQuerySucceeded()函数之前添加了2秒的超时,因为我认为这可能对您来说很方便,以防万一您在调用api(服务)后加载了新百分比。 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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