简体   繁体   中英

how to change data-value on div by JS

I am working on a project that I need to change attribute of data-value by js language.

You can see the code here.

<div class="col-sm-4">
    <div class="ldBar auto no-percent label-center m-auto" id="tree"

    style="height: 300px; width: 300px;"

  >>>>>>data-value="50"<<<<<<

     data-type="fill" data-img="tree1.svg" data-fill="data:ldbar/res,bubble(#f00,#d00,100,1)"
     data-fill-background="#ddd"
      data-fill-background-extrude="0">
      <svg xmlns:xlink="http://www.w3.org/1999/xlink"
      preserveAspectRatio="xMidYMid" width="100%" height="100%" viewBox="-4.5 -4.5 109 109">
      </svg>
      <div class="ldBar-label"></div>
    </div>
  </div>

As it seems data-value is set 50. By this I am just making image fill up to 50 per cent. But I want to change this value automatically. A Js code that makes it lets say 25. How can have this access to change this value?

You can use jQuery's .data() to get/set the attribute value:

 $('#tree').data('value', '25'); console.log($('#tree').data('value')); // 25
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-sm-4"> <div class="ldBar auto no-percent label-center m-auto" id="tree" style="height: 300px; width: 300px;" data-value="50" data-type="fill" data-img="tree1.svg" data-fill="data:ldbar/res,bubble(#f00,#d00,100,1)" data-fill-background="#ddd" data-fill-background-extrude="0"> <svg xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid" width="100%" height="100%" viewBox="-4.5 -4.5 109 109"> </svg> <div class="ldBar-label"></div> </div> </div>

This is simple pure-js example for read and write data-attributes:

 var setDataAttribute = function() { var dataContainer = document.getElementById('data-container'); var dataValue = parseInt(dataContainer.getAttribute('data-value')); dataContainer.setAttribute('data-value', dataValue + 1); dataContainer.innerHTML = dataValue + 1; }
 <div id="data-container" data-value="25">25</div> <button onclick="setDataAttribute()">increase data value</button>

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