簡體   English   中英

未從 document.getElementById 方法獲取值

[英]Not getting the value from document.getElementById method

var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
    var val = binaryValue.value;
    var result = 0;
    var i = val.length-1;
    var j = 0;
    
    while (i > -1) {
        var y = (Number(val[i])) * (2 ** [j]);
        result += y;
        i--;
        j++;
        console.log(y);
    }
    decimalValue.value = result;
    console.log(binaryValue.value);
}

使用上面的代碼,我試圖從輸入字段中獲取一個值並進行計算以將其轉換為十進制數。 但是它沒有獲取輸入值。 我嘗試了幾次,但我無法弄清楚。

這是從輸入字段中獲取值的方式:

 var binaryValue = document.getElementById('binary'); function binaryToDecimal() { var NumValue = binaryValue.value console.log("input value: " + NumValue); //this is how you convert a binary number to decimal console.log("binary number: " + (NumValue >>> 0).toString(2)); //this is how you convert an decimal number to binary console.log("decimal number: " + parseInt(NumValue, 2)); }
 <input type="text" id="binary" placeholder="insert value"/> <button type="button" onclick="binaryToDecimal()">Show value</button>

使用此示例來修復您的代碼。

我還添加了與二進制數相互轉換的方法。

暫無
暫無

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

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