2010-10-12 137 views
0

我期待打電話給我的clear() JS函數來清除我的網頁上的一些輸入字段中的文本值,但由於某種原因,函數似乎沒有被正確調用。我相信這可能是範圍問題,但我不確定。javascript函數不能調用可能是由於範圍問題

這裏是我的標記,腳本和樣式保持在一起的易於使用的當前,但一旦腳本敲定將被修補:

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Quadratic Root Finder</title> 
<script> 
function calculateQuad() 
{ 
    var inputa = document.getElementById('variablea').value; 
    var inputb = document.getElementById('variableb').value; 
    var inputc = document.getElementById('variablec').value; 

    root = Math.pow(inputb,2) - 4 * inputa * inputc; 
    root1 = (-inputb + Math.sqrt(root))/2*inputa 
    root2 = (-inputb + Math.sqrt(root))/2*inputa 

    document.getElementById('root1').value = root1; 
    document.getElementById('root2').value = root2; 
    if(root<'0') 
    { 
     alert('This equation has no real solution.') 
    } 
    else { 
     if(root=='0') 
     { 
      document.getElementById('root1').value = root1 
      document.getElementById('root2').value = 'No Second Answer' 
     } 
     else { 
      document.getElementById('root1').value = root1 
      document.getElementById('root2').value = root1 
      } 
     } 
} 
function clear() 
{ 
    document.getElementById('variablea').value = ""; 
    document.getElementById('variableb').value = ""; 
    document.getElementById('variablec').value = ""; 
} 
</script> 
<style> 
#container 
{ 
    text-align: center; 
} 
</style> 
</head> 

<body> 
<div id="container"> 
<h1>Quadratic Root Finder!</h1> 
<form id="form1"> 
    a:<input id="variablea" value="" type="text"> 
    <br/> 
    b:<input id="variableb" value="" type="text"> 
    <br /> 
    c:<input id="variablec" value="" type="text"> 
    <br /> 
    <input id="calculate" value="Calculate!" type="button" onClick="calculateQuad()"> 
    <input id="erase" value="Clear" type="button" onClick="clear()"> 
    <br /> 
    <br /> 
    Roots: 
    <br /> 
    <input id="root1" type="text" readonly> 
    <br /> 
    <input id="root2" type="text" readonly> 
</form> 
</div> 
</body> 
</html> 
+0

如果你打算要。有禮貌地使用一個福利med XHTML文檔,請不要忘記...所有屬性名稱都應該是小寫的(即使內聯事件處理程序 - 「onclick」;不是「onClick」)...實際上,你的HTML非常奇怪......你應該從自閉元素中全部刪除斜槓(換行符)。 – 2012-08-22 05:40:23

回答

2

必須重命名「清」的方法。嘗試命名它'clearFields'或其他東西。 (;

另外,如果你只想要重置表單域,你也可以這樣做: 的onClick =「this.form.reset()」

+0

Aghhhh !! :D謝謝你指出。爲什麼需要重命名?它是保留的,還是重名,還是什麼?哈哈 感謝您的替代和更容易的建議。 – Qcom 2010-10-12 00:45:12

+1

是的,'明確'是在這種情況下保留的。不用謝。 (: – aLfa 2010-10-12 00:50:58

1

可避免函數使用完全命名問題:

document.getElementById("calculate").onclick = function() { 
    ... 
}; 

document.getElementById("erase").onclick = function() { 
    ... 
}; 

這實際上是由Web開發人員添加事件處理的首選方法,因爲它避免了混亂的JavaScript嵌入片段的HTML代碼,同時保留跨瀏覽器兼容

+0

)謝謝!我也非常喜歡這個,如果使用普通的'JS',它會減少不顯眼的代碼。 – Qcom 2010-10-12 02:44:44