简体   繁体   English

使用JavaScript从HTML按钮获取值

[英]Getting the value from an HTML button using JavaScript

I am making a calculator, I have already created the calculator in html and css but I am trying to move forward by making the button clicks register in the display which is what my problem is right now. 我正在制作一个计算器,我已经用html和css创建了计算器,但是我试图通过在显示器中点击注册按钮来向前推进,这就是我现在的问题。 I am fairly new to JavaScript so if someone could point me in the right direction on how to do it or where to find the answer I would appreciate it. 我是一个相当陌生的JavaScript,所以如果有人能指出我正确的方向,如何做到这一点或在哪里找到答案我会很感激。

This is a the portion I am working on, trying to get button '7' to register so I can do the others. 这是我正在处理的部分,试图让按钮'7'进行注册,这样我就能完成其他工作。

<div class="container-fluid calc" >
 <div class="display">
  <label type="text" id="screen">0</label>

   <div class="buttons">

     <button onClick='calculate()' id='myButton'>7</button>
     <button>8</button>
     <button>9</button> 

Here is the JS I put together 这是我放在一起的JS

function calculate(){
  var num = document.getElementById('#myButton').contentValue;
  document.getElementById('screen').innerHTML = num;
}

calculate();

You should use the .innerHTML function instead of the .contentValue function to do this, also, you shouldn't use a # in document.getElementById this is used in jQuery, so just the ID is enough 您应该使用.innerHTML函数而不是.contentValue函数来执行此操作,此外,您不应该在document.getElementById使用# ,这在jQuery中使用,所以只需要ID就够了

function calculate(){
    var num = document.getElementById('myButton').innerHTML;
    document.getElementById('screen').innerHTML = num;
}

calculate();

Hope this helps! 希望这可以帮助!

You need to update from 你需要更新

 var num = document.getElementById('#myButton').contentValue;

to

 var num = document.getElementById('myButton').innerHTML;

Update 更新

function calculate(){
  var num = document.getElementById('#myButton').contentValue;
  document.getElementById('screen').innerHTML = num;
}

to

function calculate(){
  var num = document.getElementById('myButton').innerText;
  document.getElementById('screen').innerText = num;
}

Another option is you can is data attribute like this : 另一种选择是你可以像这样的数据属性:

<button onClick='calculate()' id='myButton' data-value="7">7</button>

and get it like this : 得到它像这样:

$("#myButton").attr("data-value");

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

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