為什么在給 fruit 賦值后,不需要document.write(fruit)呢,不加的時候運行正常,加了之后就報【object HTML InputElement】,求解??!
<!DOCTYPE html>
<html>
?<head>
? <title> 事件</title> ?
? <script type="text/javascript">
? ?function count(){
? ? ? ?
? ? //獲取第一個輸入框的值
? ? var num1=document.getElementById("txt1").value
? ? num1=parseInt(num1);
//獲取第二個輸入框的值
? ? var num2=document.getElementById("txt2").value
? ? num2=parseInt(num2);
//獲取選擇框的值
? ? var num3=document.getElementById("select").value
//獲取通過下拉框來選擇的值來改變加減乘除的運算法則
? ? if(num3=="+")
? ? {
? ? ? ? var sum=num1+num2;
? ? ? ? document.getElementById("fruit").value =sum;?
? ? ? ? document.write(fruit);
? ? }
? ? else if(num3 == "-")
? ? {
? ? ? ? ?var sum=num1-num2;
? ? ? ? document.getElementById("fruit").value =sum;?
? ? ? ?// document.write(fruit);
? ? }
? ? else if(num3 == "*")
? ? {
? ? ? ? var sum=num1*num2;
? ? ? ? document.getElementById("fruit").value =sum;?
? ? ? ? //document.write(fruit);
? ? }
? ? else
? ? {
? ? ? ? ?var sum=num1/num2;
? ? ? ? document.getElementById("fruit").value =sum;?
? ? ? ?// document.write(fruit);
? ? }
? ? //設置結果輸入框的值?
? ??
? ?}
? </script>?
?</head>?
?<body>
? ?<input type='text' id='txt1' />?
? ?<select id='select'>
<option value='+'>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
? ?</select>
? ?<input type='text' id='txt2' />?
? ?<input type='button' value=' = ' onclick="count()"/> <!--通過 = 按鈕來調用創建的函數,得到結果-->?
? ?<input type='text' id='fruit' /> ??
?</body>
</html>
2015-10-06
document.write(fruit);是javascript中的腳本語句,此處fruit是js的變量,你的js代碼中未給此變量定義賦值。報錯再正常不過。你所謂的給它賦值,實質上只是給html文檔結構中id為fruit的input標簽加了值。