0

我正在编写一个程序,询问购买金额,然后计算折扣价。该功能有效,但属性 innerHTML 仅在我将其设置在段落 p> 中时才有效。我希望它在输入中打印出来>。所以我的问题是我需要使用什么属性。

错误消息:未捕获的 TypeError:无法将属性“innerHTML”设置为 null

<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;

}

谢谢

http://jsfiddle.net/xK4s4/

4

2 回答 2

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>
于 2013-10-15T07:42:44.153 回答
0

  1. 删除折扣金额输入元素的 id 属性中的空格

    id="折扣金额"

  2. 设置值而不是 innerHTML。
  3. 确保您的脚本放置在输入元素之前。
工作脚本:

<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>

jsfiddle.net 中的演示

于 2013-10-15T08:02:26.997 回答