简体   繁体   English

使用javaScript将按钮中的值存储在变量中

[英]store value from button in variable using javaScript

I have two buttons and I want to store the value attribute of the button pressed into a variable called amount. 我有两个按钮,我想将按下按钮的value属性存储到一个名为amount的变量中。 The code below is clearly wrong I have two identical id's for both buttons. 下面的代码显然是错误的,两个按钮都有两个相同的ID。 What should I be doing in the function to save the value attribute to the variable amount onclick? 我应该在函数中做什么,以将value属性保存为变量onclick?

<button type="button" id='btn' onclick='storeVar' value='1'>1</button>
<button type="button" id='btn' onclick='storeVar' value='2'>2</button>
<script>
  function storeVar() {
    var amount = document.getElementById('btn').getAttribute('value');
    console.log(amount);
  } 
</script>

The attribute id must be unique in a document, use class instead. 属性ID在文档中必须唯一,而应使用 Also pass this to the function so that you can refer the current button inside the function: 也通过this来的功能,让您可以参考函数内部的当前按钮:

 function storeVar(el) { var amount = el.getAttribute('value'); // OR: simply // var amount = el.value; console.log(amount); } 
 <button type="button" class='btn' onclick='storeVar(this)' value='1'>1</button> <button type="button" class='btn' onclick='storeVar(this)' value='2'>2</button> 

Either give a unique id for each button or completely remove id attribute. 为每个按钮指定唯一的ID或完全删除ID属性。 After fixing your html try the following code. 修复html后,请尝试以下代码。

 <button type="button" id='btn' onclick='storeVar(this.value)' value='1'>1</button> <button type="button" id='btn-two' onclick='storeVar(this.value)' value='2'>2</button> <script> function storeVar(v){ let amount = v; console.log(amount); } </script> 

Make sure to have unique Id's. 确保具有唯一的ID。

<button type="button" id='btn-one' onclick='storeVar(this.value)' value='1'>1</button>
<button type="button" id='btn-two' onclick='storeVar(this.value)' value='2'>2</button>

<script>
function storeVar(value){
    let amount = value;
    console.log(amount);
}
</script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM