简体   繁体   中英

Use data-attribute in javascript to alter elements width

I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:

Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (ie graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):

<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>

The value of the data-attribute with the name "somedat" I want to use in js, like so:

var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;

What I did?

  • I checked whether the format of the value is right. I therefore set a 'static' variable var somevartest = '20%'; and used it in the code above. It worked and the graph changed accordingly.
  • I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (ie 'x%' ).

What is it that Im not getting? How can I solve my problem?

The proper way to pass data from PHP to JavaScript is using a JSON string.

PHP:

<?php
$arr = get_from_database_as_array(...);

// at end of page before your scripts:
echo "<script>";
echo "var data = " . json_encode($arr, true) . ";";
echo "</script>";

HTML:

<script>
  console.log(data); 
  document.getElementById("elem1").style.width = data["elem1"] + "px";
  document.getElementById("elem2").style.width = data["elem2"] + "px";
  // and so on.
</script>

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