单击仍带有$号的按钮时,增加数字

时间:2018-10-25 07:25:07

标签: javascript

所以我对此不敢恭维,我似乎无法弄清楚如何在有$符号的同时将数字增加1。请帮忙 :( HTML

    <section id="jackpot-container">
    <div id="jackpot">$200</div>    
</section>

<section id="buttons-container">
    <button id="increase-button" class="button">Add $1</button>
</section>

1 个答案:

答案 0 :(得分:3)

您首先需要删除$符号,将数据转换为数值(整数)并添加1,然后再添加$符号并将其显示在用户,就像这样:

document.getElementById('increase-button').addEventListener('click', function() {
  let val = document.getElementById('jackpot').textContent;
  val = parseInt(val.replace('$', '')) + 1;
  document.getElementById('jackpot').innerHTML = '$' + val;
});
<section id="jackpot-container">
  <div id="jackpot">$200</div>
</section>

<section id="buttons-container">
  <button id="increase-button" class="button">Add $1</button>
</section>