2017-07-13 49 views
1

我是web dev的新手,最近我學習了DOM。 但是,我遇到了一個困擾我的問題。 我正在嘗試製作一個簡單的球體積計算器,用戶可以通過輸入半徑來獲得球體積。無法從DOM中的輸入文本中獲取值

這是代碼。

HTML

Enter the sphere radius : <input type="number" id="radius"> 
<button id=>Calculate !</button> 
<p>Therefore, the volume of sphere are: <span id="volsphere"></span> </p> 

JS

var radius = document.querySelector("#radius"); 
var volsphere = document.querySelector("#volsphere"); 

volsphere.addEventListener("click",function(){ 
    //calculate the sphere volume 
    var spherevolume = (4/3) * Math.PI * Math.pow(radius,3); 
    //put the text content into sphere volume 
    volsphere.textContent = spherevolume ; 
}); 

我嘗試排除故障控制檯日誌radius.value和spherevolume.value工作吧。

半徑似乎是罰款,給我「3」,但球體體積有

VM97:1 Uncaught ReferenceError: spherevolume is not defined at :1:1

所以此錯誤信息,這部分代碼是給了這個錯誤? 謝謝那些幫助

+0

你得點擊收聽的,你應該把它放在按鈕。你沒有點擊跨度,是嗎? – Meggg

+0

你的標記看起來無效'' 您應該爲按鈕的id屬性填寫值或完全刪除屬性。 – tommyO

+0

@Megg我的錯誤。我應該把監聽器事件放在按鈕上 –

回答

1

問題是,你乘以HTMLElement它自己而不是它的價值。所以加.value半徑後,像這樣:

var spherevolume = (4/3) * Math.PI * Math.pow(radius.value, 3); 

不幸的是這將返回一個字符串,而不是一個數字,因此將它轉換成一個數字,你既可以把它包在parseInt()或強迫它轉成數字(即減去0)。

var spherevolume = (4/3) * Math.PI * Math.pow(parseInt(radius.value), 3); 

或者

var spherevolume = (4/3) * Math.PI * Math.pow(radius.value - 0, 3); 

在一個側面說明,你應該在button添加EventListener而不是在span。我假設你沒有這樣做,因爲整個事情都是以某種形式出現的,因此它正在重定向頁面。您可以避免通過添加一個event.preventDefault();

var button = document.querySelector("#radius+button"); 

button.addEventListener("click", function(event){ 
    var spherevolume = (4/3) * Math.PI * Math.pow(parseInt(radius.value), 3); 
    volsphere.textContent = spherevolume; 
    event.preventDefault(); 
}); 
+0

將值提取到變量中並對其執行'parseInt()'是否值得? –

+1

@NathanMontez剛編輯我的答案 –

相關問題