簡體   English   中英

如何解決這些未定義的值?

[英]How to fix these undefined values?

所以我有一個函數,我需要傳遞3個值,但是如果我不輸入它們,則我的值始終為0,如果輸入它們則為undefined。 如何解決這個問題?

<!DOCTYPE html>
<html>
<head>
    <title>Calculate Area</title>
</head>
<body>
    <h4>Enter Dimensions</h4>
    <input id="a" type="text" name=""><br>
    <input id="b" type="text" name=""><br>
    <input id="c" type="text" name=""><br>
    <input type="button" onclick="calculate()" value="Calculate">

    <div id="output"></div>


    <script>

        var a = Number(document.querySelector('#a').value);
        var b = Number(document.querySelector('#b').value);
        var c = Number(document.querySelector('#c').value);

        function calculate(a, b, c){
            //console.log(a);
            //console.log(b);
            //console.log(c);
            return 2*(a*b + a*c + b*c);
        }

        var p = calculate(a, b, c);

        document.querySelector('#output').innerHTML = `<h4>Area = ${p}</h4>`;



    </script>
</body>
</html>

您需要從元素獲取值,並將其設置為#output元素,每次調用calculate函數時。 在下面查看我的解決方案。

 var aElement = document.querySelector('#a'); var bElement = document.querySelector('#b'); var cElement = document.querySelector('#c'); var outputElement = document.querySelector('#output'); function updateArea () { var a = Number(aElement.value); var b = Number(bElement.value); var c = Number(cElement.value); var res = calculate(a, b, c); outputElement.innerHTML = `<h4>Area = ${res}</h4>`; } function calculate (a, b, c) { return 2*(a*b + a*c + b*c); } 
 <h4>Enter Dimensions</h4> <input id="a" type="text" name=""><br> <input id="b" type="text" name=""><br> <input id="c" type="text" name=""><br> <input type="button" onclick="updateArea()" value="Calculate"> <div id="output"></div> 

您正在程序開始時收集a,b和c的值。 首先,輸入框沒有任何值,因此a,b和c的值未定義。 因此,在單擊“提交”按鈕時收集值。

試試這個方法:

function calculate(){
    var a = Number(document.querySelector('#a').value);
    var b = Number(document.querySelector('#b').value);
    var c = Number(document.querySelector('#c').value);

    var p = 2*(a*b + a*c + b*c);

    document.querySelector('#output').innerHTML = '<h4>Area = ${p}</h4>';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM