【问题标题】:Multiply value of two divs and then replace one with JS将两个div的值相乘,然后用JS替换一个
【发布时间】:2018-06-19 09:53:18
【问题描述】:

我想在未来进行 A/B 测试。为此,我在 Magento 中稍微改变了购物车。我的代码是:

<ol id="cart-sidebar" class="mini-products-list clearer">
  <li class="item">
    <div class="product-details">
      <p class="product-name">Product #1</p>
      <strong>6</strong><br/>
      <span class="price">9,14&nbsp;€</span>
    </div>
  </li>
  <li class="item">
    <div class="product-details">
      <p class="product-name">Product #2</p>
      <strong>3</strong><br/>
      <span class="price">7,36&nbsp;€</span>
    </div>
  </li>
  <li class="item">
    <div class="product-details">
      <p class="product-name">Product #3</p>
      <strong>3</strong><br/>
      <span class="price">7,36&nbsp;€</span>
    </div>
  </li> 
</ol>

在每个“项目”中,我想将 &lt;strong&gt; 标记中的值乘以价格,因为它仅用于 1 的数量。然后我想用产品的实际成本替换 &lt;span class="price"&gt; 中的内容。

一种乘法可能是

var one = parseInt($(".itemOne").text(), 10);
var two = parseInt($(".itemTwo").text(), 10);
$(".total").text(one * two);

但我不知道如何替换值以及如何摆脱&amp;nbsp; 和€。也许你们有一个想法?!

【问题讨论】:

  • 使用数据属性将价格存储在 span 标签中并获取该值
  • $(".price").each(function() { var val = parseFloat($(this).text().replace(",",".")); console.log(val); }) 无需更改任何内容。我不会使用值的文本表示,但会按照 Parth 的建议进行

标签: javascript jquery html magento


【解决方案1】:

给你一个解决方案

$('li').each(function() {
  var cost = (parseFloat($(this).find('span.price').text().replace(',','.')) * parseInt($(this).find('strong').text())).toFixed(2);
  
  $(this).find('span.price').text(cost + ' €');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="cart-sidebar" class="mini-products-list clearer">
  <li class="item">
    <div class="product-details">
      <p class="product-name">Product #1</p>
      <strong>6</strong><br/>
      <span class="price">9,14&nbsp;€</span>
    </div>
  </li>
  <li class="item">
    <div class="product-details">
      <p class="product-name">Product #2</p>
      <strong>3</strong><br/>
      <span class="price">7,36&nbsp;€</span>
    </div>
  </li>
  <li class="item">
    <div class="product-details">
      <p class="product-name">Product #3</p>
      <strong>3</strong><br/>
      <span class="price">7,36&nbsp;€</span>
    </div>
  </li> 
</ol>

希望这会对你有所帮助。

【讨论】:

  • 太棒了,我没想到这么简单,我明白你在做什么,而且它有效:) 非常感谢
  • @Kesaja 欢迎好友:)
猜你喜欢
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
相关资源
最近更新 更多