javascript - Jquery - 如何从字符串中提取和计算数值

标签 javascript jquery

我需要一些帮助来根据分配给 span 文本标记的 id 从字符串中提取和计算数值。例如,我需要计算 5% 的折扣并在另一个字段中显示正确的金额。

  <span id="discount">5% off<span>
    <span id="price">£2.75</span>/per month</span> 

$( document ).ready(function() { {
    var discount= "#discount"; // a string
    discount= discount.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(discount, 10); // now it's a numeric value

    var price= "#price"; // a string
    price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(price, 10); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice= price + discount;
    $("#price").text(newPrice); 
})

我不是 Jquery 和 JavaScript 的专家,因此请理解我有限的知识,如果有人能解释如何实现预期的解决方案,我非常感激。 谢谢

最佳答案

  1. 语法错误。 document.ready 中的额外大括号
  2. 使用 jquery 选择器通过 $("#discount").text(); 获取 span 的文本

$( document ).ready(function() { 
    var discount= $("#discount").text(); // a string
   
   discount= discount.replace(/\D+/g, '');
   
    // a string of only digits, or the empty string
    var discount= parseInt(discount, 10); // now it's a numeric value

    var price= $("#price").text(); // a string
    price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(price, 10); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice= price + discount;
    $("#price").text(newPrice); 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="discount">5% off</span>
<span id="price">£2.75</span>/per month

关于javascript - Jquery - 如何从字符串中提取和计算数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44926694/

相关文章:

javascript - 为什么 Android Chrome 上的 createImageBitmap 会缩小我的图像?

javascript - 如何修改另一个站点上的变量?

javascript - AngularJS 4 可以在 IE9 上运行吗?

javascript - 如何更改 Angular.js 中 $resource 返回的数据?

jquery - 使用jquery将<br>替换为空格

JavaScript:从对象数组中删除重复项

javascript - for 循环和 promise 有问题,因为我需要遍历对象来获取值

javascript - 使用 Jquery/Javascript 使用加/减按钮同步两个输入

jquery - 最佳实践 : Jquery Ajax versus no dependence on javascript

javascript - 如何对表进行可选择的限制