[英]Getting the value from an HTML button using JavaScript
我正在制作一個計算器,我已經用html和css創建了計算器,但是我試圖通過在顯示器中點擊注冊按鈕來向前推進,這就是我現在的問題。 我是一個相當陌生的JavaScript,所以如果有人能指出我正確的方向,如何做到這一點或在哪里找到答案我會很感激。
這是我正在處理的部分,試圖讓按鈕'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>
這是我放在一起的JS
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
calculate();
您應該使用.innerHTML
函數而不是.contentValue
函數來執行此操作,此外,您不應該在document.getElementById
使用#
,這在jQuery中使用,所以只需要ID就夠了
function calculate(){
var num = document.getElementById('myButton').innerHTML;
document.getElementById('screen').innerHTML = num;
}
calculate();
希望這可以幫助!
你需要更新
var num = document.getElementById('#myButton').contentValue;
至
var num = document.getElementById('myButton').innerHTML;
更新
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
至
function calculate(){
var num = document.getElementById('myButton').innerText;
document.getElementById('screen').innerText = num;
}
另一種選擇是你可以像這樣的數據屬性:
<button onClick='calculate()' id='myButton' data-value="7">7</button>
得到它像這樣:
$("#myButton").attr("data-value");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.