我需要一些帮助来根据分配给 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 的专家,因此请理解我有限的知识,如果有人能解释如何实现预期的解决方案,我非常感激。 谢谢
最佳答案
- 语法错误。 document.ready 中的额外大括号
- 使用 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/