简体   繁体   中英

How do you convert cm values to inches and replace the text "cm" to "in"? Javascript

Trying to recreate a garment measurement chart I've seen but in pure Javascript. But I'm having trouble figuring out how to grab the number value in innerhtml and multiply/divide it by * 2.54. Additionally i'd like to add "cm" or "in" at the end of the number to indicate the metric system.

https://jsfiddle.net/kud8sj7w/5/

<div id="xs-sizes">
        <li class="measurement" style="left: 15%; top: 33%;">
            63.5
        </li><li class="measurement" style="left: 48%; top: 16%;">
            43.5
        </li><li class="measurement" style="left: 48%; top: 79%;">
            50.5
        </li><li class="measurement" style="left: 48%; top: 50%;">
            43
        </li><li class="measurement" style="left: 83%; top: 62%;">
            64.5
        </li>
        
 function convert() {
      var measurements = document.getElementsByClassName("measurement");
      
       for(var i = 0; i < measurements.length; i++){
       
          measurements[i].innerHTML = valNum * 2.54;
       }
  }

You need to store the current state to know whether you need to convert or not. In your case, initially 'CM'

 let cur_measurement = 'CM';

 function convert() {
   let measurements = document.getElementsByClassName("measurement");
   let CM = document.querySelector('input[value="CM"]');
   let IN = document.querySelector('input[value="IN"]');
   
   let ratio = 0;
   if(CM.checked && cur_measurement != 'CM'){
        ratio = 2.54;
      cur_measurement = 'CM';
   } else if (IN.checked && cur_measurement != 'IN' ){
        ratio = 1/2.54;
      cur_measurement = 'IN';
   }

   for (var i = 0; i < measurements.length; i++) {
        let cur_val = parseFloat(measurements[i].innerText);
        measurements[i].innerText = Math.round(cur_val * ratio * 10) / 10;
   }
 }

So for measurements[i].innerHTML = valNum * 2.54; , valNum is undefined. Look at convert() there's no parameters. So when it's called it multiplies by valNum which is undefined .

Think about what valNum should equal to or what 2.54 should be operating on. I hope that helps. Also to string the cm/unit, you can just concatenate but get the result first.

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