javascript函数不能调用可能是由于范围问题

问题描述:

我期待打电话给我的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

必须重命名“清”的方法。尝试命名它'clearFields'或其他东西。 (;

另外,如果你只想要重置表单域,你也可以这样做: 的onClick =“this.form.reset()”

+0

Aghhhh !! :D谢谢你指出。为什么需要重命名?它是保留的,还是重名,还是什么?哈哈 感谢您的替代和更容易的建议。 – Qcom 2010-10-12 00:45:12

+1

是的,'明确'是在这种情况下保留的。不用谢。 (: – aLfa 2010-10-12 00:50:58

可避免函数使用完全命名问题:

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

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

这实际上是由Web开发人员添加事件处理的首选方法,因为它避免了混乱的JavaScript嵌入片段的HTML代码,同时保留跨浏览器兼容

+0

)谢谢!我也非常喜欢这个,如果使用普通的'JS',它会减少不显眼的代码。 – Qcom 2010-10-12 02:44:44