【问题标题】:javascript function not calling possibly due to scope issuejavascript 函数未调用可能是由于范围问题
【发布时间】:2011-04-24 01:56:27
【问题描述】:

我希望调用我的clear() JS 函数来清除我网页上某些输入字段中的文本值,但由于某种原因,该函数似乎没有被正确调用。我相信这可能是一个范围问题,但我不确定。

这是我的标记、脚本和样式,目前为了便于使用而保存在一起,但在脚本完成后会进行修改:

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

【问题讨论】:

  • 如果您要礼貌地使用格式良好的 XHTML 文档,请不要忘记...所有属性名称都应该小写(即使是内联事件处理程序——“onclick "; 不是 "onClick")...实际上,您的 HTML 很奇怪...您应该将自闭合元素中的斜杠一起删除(换行符)。

标签: javascript function methods scope


【解决方案1】:

您必须重命名“清除”方法。尝试将其命名为“clearFields”或其他名称。 (;

此外,如果您只想重置表单字段,您也可以这样做: onClick="this.form.reset()"

【讨论】:

  • 啊啊啊!! :D 感谢您指出这一点。为什么需要重命名呢?它是保留的,还是重复的名称,还是什么?哈哈,也感谢您提供替代且更简单的建议。
  • 是的,'clear' 在这种情况下是保留的。不客气。 (:
【解决方案2】:

您可以使用以下方法完全避免函数命名问题:

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

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

这实际上是 Web 开发人员添加事件处理程序的首选方法,因为它避免了 HTML 代码与 JavaScript 的内联 sn-ps 混淆,同时保持跨浏览器兼容性。

【讨论】:

  • 谢谢!我也非常喜欢这个,如果使用普通的 JS,它可以减少不显眼的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多