【问题标题】:Append to value attribute on button click在按钮单击时附加到值属性
【发布时间】:2021-05-31 14:34:27
【问题描述】:

每次单击按钮时,我都会尝试修改输入。有点像计算器。将从 0 开始。当我单击按钮“7”时,它的值将更改为 7,当我单击“4”时,它将更改为 74。基本上就像一个计算器。

我编写的这段代码确实修改了输入的 ,但是我似乎找不到如何追加更多值到那个值。这是我的代码。有人可以帮我吗?

<input class="normal-input" type="number" step="0.01"> <!-- Value is NULL-->
<button value="7" class="my-buttons" type="button"> 7 </button> <!--Button to change the value of the input-->

 $('.my-buttons').click(function(){
     $(".normal-input").attr("value", $(this).attr('value'));
 }); <!-- The actual function. -->

如您所见,该函数完全用新值替换了以前的值。我希望它像计算器一样附加值。

【问题讨论】:

    标签: javascript html jquery forms jquery-events


    【解决方案1】:

    我建议你尝试这样做:

    • 将值初始化为零
    • 每当调用 click 时,将当前值乘以 10,然后添加按钮值。
    • 您可以根据用例删除 step 属性。

    【讨论】:

      【解决方案2】:

      在这个函数中:

      $(".normal-input").attr("value", $(this).attr('value'));
      

      第二个参数是要设置的值:

      $(this).attr('value')
      

      您需要将其作为先前值和新值的组合:

      $(".normal-input").attr('value') + '' + $(this).attr('value')
      

      空白字符串是为了确保最终结果是一个字符串,而不是2个数字相加。

      如果你想把它转换成数字,你可以使用 parseInt():

      const combinedNumber = $(".normal-input").attr('value') + '' + $(this).attr('value')
      const intNumber = parseInt(combinedNumber)
      

      最终代码可能类似于:

      <input class="normal-input" type="number" step="0.01"> <!-- Value is NULL-->
      <button value="7" class="my-buttons" type="button"> 7 </button> <!--Button to change the value of the input-->
      
      
      
      $('.my-buttons').click(function(){
      
          const existingValue = $(".normal-input").attr('value')
          const newValue = $(this).attr('value'
          const combinedValue = parseInt(existingValue + '' + newValue)
          $(".normal-input").attr("value", combinedValue);
      
       }); <!-- The actual function. -->
      

      【讨论】:

      • 您好!我试过用这个,但它不太管用。我也将其修改为: $(".normal-input").attr('value', 'value' + $(this).attr('value'));你知道会发生什么吗?
      • 我已编辑回复以提供完整的解决方案 - 如果效果更好,请告诉我
      【解决方案3】:

      您只需concat 实际值和单击按钮的值即可获取所需值。

      演示代码

      $('.my-buttons').click(function() {
        var value = $(".normal-input").val()
        var clicked_button = $(this).attr('value')
        //use val and combined both value
        $(".normal-input").val(value + "" + clicked_button);
      
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <input class="normal-input" type="number">
      <button value="7" class="my-buttons" type="button"> 7 </button>
      <button value="10" class="my-buttons" type="button"> 10 </button>
      <button value="6" class="my-buttons" type="button"> 6 </button>

      【讨论】:

        猜你喜欢
        • 2019-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-04
        • 1970-01-01
        • 2017-04-05
        相关资源
        最近更新 更多