【问题标题】:How can we add a "+" at the end of a number in JavaScript我们如何在 JavaScript 中的数字末尾添加“+”
【发布时间】:2020-08-24 09:50:46
【问题描述】:

我有一段代码在用户滚动到它时开始递增。 sn-p 代码不是我的。作者是大卫·雷斯。但这与我所做的非常相似。

var a = 0;
$(window).scroll(function() {

  var oTop = $('#counter').offset().top - window.innerHeight;
  if (a == 0 && $(window).scrollTop() > oTop) {
    $('.counter-value').each(function() {
      var $this = $(this),
        countTo = $this.attr('data-count');
      $({
        countNum: $this.text()
      }).animate({
          countNum: countTo
        },

        {

          duration: 2000,
          easing: 'swing',
          step: function() {
            $this.text(Math.floor(this.countNum));
          },
          complete: function() {
            $this.text(this.countNum);
            //alert('finished');
          }

        });
    });
    a = 1;
  }

});
.fake-div {
  width: 100%;
  height: 1280px;
  position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fake-div">
</div>
<div id="counter">
  <div class="counter-value" data-count="300">0</div>
  <div class="counter-value" data-count="400">100</div>
  <div class="counter-value" data-count="1500">200</div>
</div>
<div class="fake-div">
</div>

但最后,当它完成时,我希望他们在它的末尾有一个“+”。

例如,我希望最终结果类似于以下数字: 300+ 400+ 1500+

【问题讨论】:

  • console.log(300 + "+")
  • 但这只会在控制台中打印出来。
  • 重点是 JavaScript + 操作符“首选”字符串,所以如果将字符串“添加”到数字,结果就是字符串。

标签: javascript html css increment auto-increment


【解决方案1】:

只需将字符串添加到数字的末尾

var 变量 = 数字 + "+";

如果你愿意,你可以看看

函数 myFunction() {

var str1 = "Hello ";
var str2 = "world!";
var str3 = " Have a nice day!";
var res = str1.concat(str2, str3);
document.getElementById("demo").innerHTML = res;

}

那是使用 javascript concat() 方法,但在你的情况下可能是矫枉过正。

【讨论】:

  • 我尝试过使用 concat 函数,但没有成功。您能否尝试将其添加到 sn-p 并显示给我看。那将是一个很大的帮助!非常感谢
  • @AbhisarAnand 如果你有“不成功”的代码,你应该在你的问题中发布它。这就是这个网站的运作方式。
  • 在你的完整功能上,试试 $this.text(this.countNum+"+");而不是 $this.text(this.countNum);这应该只是将字符串“+”添加到计数器的末尾。
猜你喜欢
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 2015-07-25
  • 1970-01-01
  • 2018-12-22
  • 2020-01-07
  • 2016-06-19
相关资源
最近更新 更多