如何從 span 標籤獲取價格值並在用 JavaScript 乘以數字後將它新增到 div 內?


提取值並將其從字串轉換為整數,以便從 span 標籤中獲取價格值。

示例

以下為程式碼 −

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<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>

要執行以上程式,請儲存檔名 anyName.html(index.html),然後右鍵單擊該檔案。在 VS 程式碼編輯器中選擇選項“使用即時伺服器開啟”。

這將生成以下輸出 -

以下為控制檯上的輸出 -

這將生成以下輸出 -

這將在控制檯上生成以下輸出 -

更新於: 2020-10-24

1 千多人次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始學習
廣告
© . All rights reserved.