【问题标题】:How to change code depending on a clicked button如何根据单击的按钮更改代码
【发布时间】:2021-01-08 20:55:05
【问题描述】:

我在 HTML 中定义了两个按钮,[Male] 和 [Female]。

<div class="gender-buttons" id="gender-buttons">
   <button class="male-button">MALE</button>
   <button class="female-button">FEMALE</button>
</div>

我希望按钮的值设置如下

  • [男性] = 0.55
  • [女性] = 0.68

用户将点击他们的性别然后将启动一个功能。

<script>
  function calculate(){
    const genderMultiplier = document.getElementById("gender-buttons");
    return genderMultiplier * 100;
  };
</script>

如何将我的 HTML 连接到 JavaScript,以便当用户单击男性时,该函数将在函数中使用 0.55,反之亦然?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    您是否尝试过为按钮使用onClick 事件和value 属性?

    function calculate(target){
       var genderVal = target.value * 100
       console.log(genderVal) // for your information - can remove
       return genderVal
    }
    <div class="gender-buttons" id="gender-buttons">
       <button class="male-button" value=0.55 onClick="calculate(this)">MALE</button>
       <button class="female-button" value=0.68 onClick="calculate(this)">FEMALE</button>
    </div>

    【讨论】:

      【解决方案2】:

      在按钮中添加onclick事件,使用值来计算...

      <div class="gender-buttons" id="gender-buttons">
         <button class="male-button" onclick="calculate(0.55)">MALE</button>
         <button class="female-button" onclick="calculate(0.68)">FEMALE</button>
      </div>
      
      <script>
          function calculate(genderMultiplier){
              genderMultiplier * 100;
              return genderMultiplier; //use this variable where ever you want.
          }
      </script>
      

      【讨论】:

        【解决方案3】:

        我认为你可以使用name-value 对。

        如:

        <button class="gender-button" name="male" value="0.55" onclick="calculate(this.value)">MALE</button>
        
        <button class="gender-button" name="female" value="0.68" onclick="calculate(this.value)">FEMALE</button>
        

        然后,通过调用onclick 处理按钮中的值。

        <script>
           function calculate(genderMultipiler){
               let result = genderMultipiler * 100;
               return result;
           };
        </script>
        

        【讨论】:

          【解决方案4】:

          你可以这样做;

          在 HTML 中将性别值传递给函数;

          <div class="gender-buttons" id="gender-buttons">
             <button class="male-button" onclick="calculate(0.55)">MALE</button>
             <button class="female-button" onclick="calculate(0.68)">FEMALE</button>
          </div>
          

          在js函数中;

          function calculate(val){
          let genderMultiplier = val * 100;
          
          return genderMultiplier;
          };
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-10-10
            • 2020-02-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-25
            • 1970-01-01
            相关资源
            最近更新 更多