为什么我的InnerHTML代码不会在表单字段中显示任何数据?

时间:2019-11-05 03:08:18

标签: javascript

我做了一个简单的找零计算器。在玩完代码之后,我设法使其计算所需的值,但无法使其填充我的表单。如果我使用alert,该函数是正确的,但是如果我尝试使用innerHTML来填充字段,则什么也不会发生。我真的被这个困住了。 :(

var quarters;
var dimes;
var nickels;
var pennies;

function Calculate() {
    if (cents >= 25) {
        quarters = Math.floor(cents / 25);
        var qreminder = cents % 25;

        if (qreminder <= 24) {
            dimes = Math.floor(qreminder / 10);
            var dreminder = qreminder % 10;
        }
        if (dreminder < 10) {
            nickels = Math.floor(dreminder / 5);
            var nreminder = dreminder % 5;
        }
        if (nreminder < 5) {
            pennies = nreminder / 1;
        }
        document.getElementById("quarters").innerHTML = quarters;
        document.getElementById("dimes").innerHTML = dimes;
        document.getElementById("nickels").innerHTML = nickels;
        document.getElementById("pennies").innerHTML = pennies;

    }
    if (cents < 25) {
        quarters = Math.floor(cents / 25);
        var qreminder = cents % 25;

        if (qreminder <= 24) {
            dimes = Math.floor(qreminder / 10);
            var dreminder = qreminder % 10;
        }
        if (dreminder < 10) {
            nickels = Math.floor(dreminder / 5);
            var nreminder = dreminder % 5;
        }
        if (nreminder < 5) {
            pennies = nreminder / 1;
        }
        document.getElementById("quarters").innerHTML = quarters;
        document.getElementById("dimes").innerHTML = dimes;
        document.getElementById("nickels").innerHTML = nickels;
        document.getElementById("pennies").innerHTML = pennies;
    }
}
var cents = document.getElementById("cents").value;
document.getElementById("calculate").addEventListener("click", Calculate);
	
<div id="content">
    <h1>Change Calculator</h1>
    <label>Enter number of cents (0-99):</label>
    <input type="text" id="cents" />
    <input type="button" value="Calculate" name="calculate" id="calculate" /><br />
    <p>&nbsp;</p>
		
    <label>Quarters:</label>
    <input type="text" id="quarters" class="disabled" disabled="disabled" /><br />
					
    <label>Dimes:</label>
    <input type="text" id="dimes" class="disabled" disabled="disabled" /><br />
	
    <label>Nickels:</label>
    <input type="text" id="nickels" class="disabled" disabled="disabled" /><br />
		
    <label>Pennies:</label>
    <input type="text" id="pennies" class="disabled" disabled="disabled" /><br />
					
    <p>&nbsp;</p>

1 个答案:

答案 0 :(得分:1)

设置<input>类型的.innerHTML属性不会执行任何操作。而是设置这些元素的.value属性。

document.getElementById("quarters").value = quarters;
document.getElementById("dimes").value = dimes;
document.getElementById("nickels").value = nickels;
document.getElementById("pennies").value = pennies;