繁体   English   中英

使用普通JavaScript修剪输入标签范围中的小数

[英]Trim decimals from input label span using plain JavaScript

我使用的是一个wordpress插件,它吐出的代码看起来像这样:

<div class=" product-addon product-addon-extra-tip">    
  <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-0">
    <label>
      <input type="radio" class="addon addon-radio" name="addon-2004-extra-tip-0[]" data-raw-price="2" data-price="2" value="2"> $2 (<span class="amount">$2.00</span>)</label>
  </p>
  <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-1">
    <label>
      <input type="radio" class="addon addon-radio" name="addon-2004-extra-tip-0[]" data-raw-price="5" data-price="5" value="5"> $5 (<span class="amount">$5.00</span>)</label>
  </p>
</div>

您可以看到<span>包含带小数的美元值。 我想修剪每个实例的十进制和尾随零。

我知道使用toFixed()应该可以实现,但是我无法弄清楚到底如何仅针对那些特定的<span> 我不能简单地用的类名来选择amount ,因为它是在别处使用。

因此,我需要使用product-addon类将<span> s定位为<div>内的类amount 我需要从这些<span>的字符串中删除小数。

因此,使用querySelectorAll并选择它们

var spans = document.querySelectorAll("dov.product-addon span.amount");
console.log(spans.length);

并遍历集合。

使用以下javascript使用class product-addon修剪div spans内的所有小数和尾随零。

 var links = document.getElementsByClassName("product-addon"); var span = links[0].getElementsByTagName("span"); console.log(span.length); for (var i = 0; i < span.length; i++) { span[i].innerText = span[i].innerText.split('.')[0]; } 
 <div class=" product-addon product-addon-extra-tip"> <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-0"> <label> <input type="radio" class="addon addon-radio" name="addon-2004-extra-tip-0[]" data-raw-price="2" data-price="2" value="2">$2 (<span class="amount">$2.00</span>)</label> </p> <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-1"> <label> <input type="radio" class="addon addon-radio" name="addon-2004-extra-tip-0[]" data-raw-price="5" data-price="5" value="5">$5 (<span class="amount">$5.00</span>)</label> </p> </div> 

暂无
暂无

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

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