【问题标题】:transform a positive number to a negative number将正数转换为负数
【发布时间】:2020-08-27 14:37:39
【问题描述】:

我想使用减号将数​​字显示为负数:5000 --> - 5000

<div class="cart-summary-line" id="cart-subtotal-discount">
  <span class="label">
    Remise
  </span>
  <span class="value">5,000&nbsp;TND</span>
</div>

这是我在自定义 JS 中的文章,但数字仍然显示为正数。

$(document).ready(function() {
  return "-" + ($(['#cart-subtotal-discount'.value]).html(5.000));
});

【问题讨论】:

  • 将值乘以-1
  • 感谢@BenBrookes 的回复。你的意思是 $(['#cart-subtotal-discount' .value*(-1)]) ??
  • $(['#cart-subtotal-discount' .value]) 真的没有意义。如果你知道这个数字是正数,你可以做$('#cart-subtotal-discount .value').prepend('-')。或者更好的是,一个 CSS 规则 #cart-subtotal-discount .value::before { content: "-"; }

标签: javascript html negative-number


【解决方案1】:

您的 JavaScript 和 jQuery 语法有很多问题。我建议重新阅读jQuery documentation and examples

$(document).ready(function() {
  return "-"+($(['#cart-subtotal-discount'.value]).html(5.000));
// ^ we don't need the return value
//        ^ concatenating a "-" here won't set anything
//           ^ don't need the extra parentheses here
//              ^ why square brackets? this isn't an array
//                ^ this selector contains a lot more text than just the number
//                                        ^ do we want `value` or `html`?
//                                        ^ are we getting, setting, or both?
//                                                      ^ `5.000` means `5` in JS, not `5000`

});

以下是您可能实现目标的一种方法:

const positiveNumber = 5000
const negativeNumber = 0 - positiveNumber
const locale = 'ar-TN' // Tunisian locale, assumed from "TND" currency

// Using `toLocaleString` with the ar-TN locale will give you
// the "5.000" formatting you want, but you still need to
// write the number as `5000` in JavaScript.
const formattedNumber = negativeNumber.toLocaleString(locale)

$(document).ready(function() {
  $('#amount').html(formattedNumber)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Remise <span id="amount"></span>&nbsp;TND</p>

【讨论】:

    猜你喜欢
    • 2011-12-13
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 2014-03-20
    • 1970-01-01
    相关资源
    最近更新 更多