我正在编写一个程序,询问购买金额,然后计算折扣价。该函数有效,但属性innerHTML仅在我将其设置在段落p>中时才有效。我希望它在输入>中打印出来。所以我的问题是我需要使用什么属性。
错误讯息: 未捕获的TypeError:无法设置null
的属性'innerHTML'<body>
<p>Enter amount of purchases:<input type =" text" id ="purchase_amount" onkeyup ="calculate_discount()"/></p>
<p>Discount price:<input type="text" id =" discount_amount"/></p>
</body>
function calculate_discount() {
var purchase_amount = document.getElementById("purchase_amount").value;
var answer;
if (purchase_amount >= 10)
{
answer = purchase_amount - (purchase_amount * .10);
}
else if (purchase_amount < 10)
{
answer = purchase_amount;
}
document.getElementById("discount_amount").innerHTML = answer;
}
谢谢
答案 0 :(得分:0)
输入元素不使用innerHTML
属性,而是设置value
属性。
document.getElementById("discount_amount").value = answer;
其他问题:
在小提琴中,运行代码onload
,这意味着您的函数不在全局范围内,并且无法通过keyup事件调用。更改为no wrap - in head
。
您在discount_amount元素ID之前有一个空格:
<p>Discount price:<input type="text" id =" discount_amount"/></p>
答案 1 :(得分:0)
的id属性中的空格
id =“discount_amount”
<script>
function calculate_discount() {
var purchase_amount = document.getElementById("purchase_amount").value;
var answer;
if (purchase_amount >= 10)
{
answer = purchase_amount - (purchase_amount * .10);
}
else if (purchase_amount < 10)
{
answer = purchase_amount;
}
document.getElementById("discount_amount").value = answer;
}
</script>
<body>
Enter amount of purchases:
<input type="text" id="purchase_amount" onkeyup="calculate_discount()"/>
Discount price:
<input type="text" id="discount_amount"/>
</body>