我要计算转化率。
Conversion Rate = Total Number of Sales / Number of Leads * 100
我有div
框,上面有我要从中获取这些数字的类。 .box-1 1 .total-number
和.box-1 .leads-number
<div class="box-1">
<div class="total-number">400</div>
<div class="leads-number">800</div>
</div>
答案 0 :(得分:1)
您可以使用jquery的.text()
方法来获取div的值,并使用.text(value)来为div设置文本,
function calculate(){
let totalNumber = $('.total-number').text();
let leadNumber = $('.leads-number').text();
let rate = (totalNumber) * 100 / leadNumber;
$('.conversion-rate').text(rate);
}
更新:
如果不需要单击“计算”按钮,则将代码移到外部
let totalNumber = $('.total-number').text();
let leadNumber = $('.leads-number').text();
let rate = (totalNumber) * 100 / leadNumber;
$('.conversion-rate').text(rate);
//function calculate(){
let totalNumber = $('.total-number').text();
let leadNumber = $('.leads-number').text();
let rate = (totalNumber) * 100 / leadNumber;
$('.conversion-rate').text(rate);
//}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-1">
<div class="total-number">400</div>
<div class="leads-number">800</div>
<div class='conversion-rate'></div>
<!--<input type='button' value='Calculate' onclick='calculate()' />-->
</div>
答案 1 :(得分:1)
尝试一下:
const totalNumber = +document.querySelector('.total-number').textContent;
const leadsNumber = +document.querySelector('.leads-number').textContent;
const rate = totalNumber/leadsNumber*100;
console.log(rate)
<div class="box-1">
<div class="total-number">400</div>
<div class="leads-number">800</div>
</div>
答案 2 :(得分:0)
使用innerHTML
和trim
从两个div中获取文本内容,以删除空格。
let totalNum = document.querySelector('.box-1').querySelector('.total-number').innerHTML.trim();
let leadNum = document.querySelector('.box-1').querySelector('.leads-number').innerHTML.trim();
let rate = (totalNum) * 100 / leadNum;
console.log(rate)
<div class="box-1">
<div class="total-number">400</div>
<div class="leads-number">800</div>
</div>