2013-01-16 35 views
-1

我的代碼(微型計算器應用程序):(HTML/JS)的JavaScript的onClick在腳本標籤

<input class="value" type="text" id="first" /> 
<input class="value" type="text" id="second" /> 
<input class="value" type="text" id="result" /> 
<input class="button" type="button" value="+" id="plus" /> 

window.onLoad = function motor() 
{ 
    var plus = document.getElementById("plus"); 

    function updateResult(act) 
    { 
     var first = parseFloat(document.getElementById("first").value); 
     var second = parseFloat(document.getElementById("second").value); 
     if (isNaN(first)) first = 0; 
     if (isNaN(second)) second = 0; 

     if (act == '+') { 
      document.getElementById("result").value = first + second; 
     } 
    } 
    plus.onClick = updateResult('+'); 
} 

至極不工作:(我需要的onClick行動時,按下按鈕, 「ID」

回答

2

您分配函數調用onclick事件。你是不是分配給函數的引用的結果。

而且,點擊事件名稱使用情況c。

plus.onclick = function(){updateResult('+');}; 
+0

仍然不起作用! – user1906992

+0

我錯過了你有大寫字母C的事實。這個事件是區分大小寫的。我已經通過@svidgen解決了它! – epascarello

+0

謝謝! Realy ..現在工作。我現在更快樂:3 – user1906992

1

想要將plus對象的onClick屬性設置爲函數,而不是調用updateResult()(這是未定義的)的結果。實現這一目標的方法之一是讓updateResult()返回一個函數:

window.onLoad = function motor() 
{ 
    var plus = document.getElementById("plus"); 

    function updateResult(act) 
    { 
     return function(){ 
      var first = parseFloat(document.getElementById("first").value); 
      var second = parseFloat(document.getElementById("second").value); 
      if (isNaN(first)) first = 0; 
      if (isNaN(second)) second = 0; 

      if (act == '+') { 
       document.getElementById("result").value = first + second; 
      } 
     }; 
    } 
    plus.onclick = updateResult('+'); 
} 
+0

這是onclick :)你有我的帖子相同的問題! – epascarello

+0

感謝您修復它 - 通常我甚至不會在此分配處理程序,所以我只專注於手頭的問題。 – jimbojw

0

這是onclick,不onClick

請確保案件是正確的。

1
//JS is case-sensitive, the correct property name is `onload` not onLoad 
window.onload = function motor() 
[...] 
    //onclick not onClick 
    plus.onclick = function() { 
     //you need to assign a function to execute on `onclick` instead of 
     //the return value of calling it with() which you were doing previously 
     updateResult('+'); 
    }; 

Fiddle

此外,如JSHint考慮使用代碼質量分析工具。即使它可能無法捕獲這些錯誤類型,因爲它們對這些對象創建新的屬性是「有效的」,它應該在將來幫助你。另外,如果您對如何使用函數或屬性或其正確的拼寫/語法存在疑問,則可以查看MDN。例如,window.onload docs