Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy giá trị giá từ thẻ span, nhân 10 và hiển thị trong div bằng JavaScript/jQuery

Mô tả

Trích xuất text từ thẻ span có class "purchase amount", chuyển sang số, nhân 10, hiển thị kết quả vào thẻ p#demo.

Code HTML + JavaScript/jQuery

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
  <tr>
    <th>Value=</th>
    <td><strong><span class="purchase amount"><span></span>10</span></strong></td>
    <p id="demo"></p>
  </tr>
</body>
<script>
  $(document).ready(function() {
    var v = parseInt($(".purchase.amount").text().trim().replace(',', ''));
    var totalValue = v * 10;
    console.log(totalValue);
    $("#demo").text("After multiplying the Value 10=" + totalValue);
  });
</script>
</html>

Giải thích

  1. $(".purchase.amount") chọn span có cả 2 class
  2. .text() lấy text content
  3. .trim().replace(',', '') làm sạch
  4. parseInt() chuyển sang số
  5. $("#demo").text(...) gán text cho p#demo

Vanilla JS (không jQuery)

const span = document.querySelector('.purchase.amount');
const value = parseInt(span.textContent.trim().replace(',', ''));
document.getElementById('demo').textContent = `After multiplying the Value 10=${value * 10}`;