我需要一些帮助,根据分配给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的遗嘱因此请理解我的有限知识,如果有人能解释如何实现预期的解决方案,我感谢你。 感谢
答案 0 :(得分:1)
$("#discount").text();
$( 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);
})
&#13;
<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
&#13;
答案 1 :(得分:0)
假设您的输入(价格和折扣)是基于输入的条目,您可以使用提供的Regex从字符串中提取数字(假设一次只有一组数字)。
$( document ).ready(function() {
var discount= $("#discount").text(); // a string
discount = Regex.Replace(discount, @"[^\d]", ""); // a string of only digits, or the empty string
discount = parseInt(discount); // now it's a numeric value
var price= $("#price").text(); // a string
price = Regex.Replace(price, @"[^\d]", ""); // a string of only digits, or the empty string
price = parseFloat(price); // now it's a numeric value
var discountValue = (discount * price) / 100;
var newPrice = price + discount;
$("#price").text(newPrice);
})
答案 2 :(得分:0)
我真的建议在业务逻辑中解决这个问题,而不是在前端使用jquery。
$(function(){
var pattern = /[^0-9\.]/g;
var discount = parseFloat($('#discount').html().replace(pattern, ""));
var price = praseFloat($('#price').html().replace(pattern, ""));
var result = price - price * (discount/100);
console.log(result);
});
更新
没有jquery:
(function(d){
var pattern = /[^0-9\.]/g;
var discount = parseFloat(d.querySelector('#discount').innerHTML.replace(pattern, ""));
var price = praseFloat(d.querySelector('#price').innerHTML.replace(pattern, ""));
var result = price - price * (discount/100);
console.log(result);
}(document);
为什么要使用自动执行的匿名函数?保持全局范围清洁并使这些变量的垃圾收集成为可能。