如何根据单击的按钮更改代码

我在 HTML 中定义了两个按钮,[男性] 和 [女性]。


<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,以便当用户单击male 时,该函数将在函数中使用 0.55,反之亦然?


一只甜甜圈
浏览 52回答 4
4回答

有只小跳蛙

您是否尝试过使用按钮的onClick事件和属性?valuefunction calculate(target){&nbsp; &nbsp;var genderVal = target.value * 100&nbsp; &nbsp;console.log(genderVal) // for your information - can remove&nbsp; &nbsp;return genderVal}<div class="gender-buttons" id="gender-buttons">&nbsp; &nbsp;<button class="male-button" value=0.55 onClick="calculate(this)">MALE</button>&nbsp; &nbsp;<button class="female-button" value=0.68 onClick="calculate(this)">FEMALE</button></div>

胡说叔叔

在按钮中添加一个onclick事件,使用值来计算...<div class="gender-buttons" id="gender-buttons">&nbsp; &nbsp;<button class="male-button" onclick="calculate(0.55)">MALE</button>&nbsp; &nbsp;<button class="female-button" onclick="calculate(0.68)">FEMALE</button></div><script>&nbsp; &nbsp; function calculate(genderMultiplier){&nbsp; &nbsp; &nbsp; &nbsp; genderMultiplier * 100;&nbsp; &nbsp; &nbsp; &nbsp; return genderMultiplier; //use this variable where ever you want.&nbsp; &nbsp; }</script>

守着星空守着你

我认为你可以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>&nbsp; &nbsp;function calculate(genderMultipiler){&nbsp; &nbsp; &nbsp; &nbsp;let result = genderMultipiler * 100;&nbsp; &nbsp; &nbsp; &nbsp;return result;&nbsp; &nbsp;};</script>

慕侠2389804

你可以这样做;在 HTML 中将性别值传递给函数;<div class="gender-buttons" id="gender-buttons">&nbsp; &nbsp;<button class="male-button" onclick="calculate(0.55)">MALE</button>&nbsp; &nbsp;<button class="female-button" onclick="calculate(0.68)">FEMALE</button></div>在js函数中;function calculate(val){let genderMultiplier = val * 100;return genderMultiplier;};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript