【问题标题】:Javascript function in header showing as undefined标头中的 Javascript 函数显示为未定义
【发布时间】:2013-02-04 08:12:03
【问题描述】:
    <script type="text/javascript">
function centerItem(id,size)
{
    var pad = (window.innerWidth - size)/2;
    document.getElementById(id).style.marginLeft = pad+"px";
    document.getElementById(id).style.marginRight = pad+"px";
}

function login()
{
    document.getElementById('box').innerHTML="<img src="img/pleasewait.gif" />";
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById('box').innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","http://[lan ip]/Athena/lib/ajax/login.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("email="+email+"&pass="+pass);
}
</script>

那在我的&lt;head&gt; 部分,我用这个来称呼它。

<script type="text/javascript">centerItem('login',210);</script>

但是,我收到一条错误消息,提示“未捕获的 ReferenceError:未定义 centerItem (匿名函数)”

有什么想法吗?

【问题讨论】:

  • 调用函数的&lt;script&gt;标签在哪里?在&lt;head&gt;&lt;body&gt;?
  • 另外,你应该这样调用你的函数:centerItem('login',210);
  • centerItem 的参数列表中缺少逗号。
  • 该函数位于 中,而调用位于
    之后的 中,带有 id。
  • 缺少逗号是因为第二个代码部分没有复制/粘贴,而是匆忙输入,就像我原来的那样。

标签: javascript html function centering


【解决方案1】:

document.getElementById('box').innerHTML="&lt;img src="img/pleasewait.gif" /&gt;";
真的应该是:
document.getElementById('box').innerHTML="&lt;img src=\"img/pleasewait.gif\" /&gt;"

创建图片标签时需要对双引号进行转义。

你应该缓存你选择的元素。结果会是这样的:

function centerItem(id, size) {
    var pad = (window.innerWidth - size)/2,
        elem = document.getElementById(id);
    elem.style.marginLeft = pad+"px";
    elem.style.marginRight = pad+"px";
}

function login() {
    var xmlhttp;
    var box = document.getElementById('box');
    box.innerHTML="<img src=\"img/pleasewait.gif\" />";

    if (window.XMLHttpRequest){
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    } else {
      // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            box.innerHTML=xmlhttp.responseText;
        }
    };
    xmlhttp.open("POST","http://[lan ip]/Athena/lib/ajax/login.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("email="+email+"&pass="+pass);
}

【讨论】:

  • 谢谢!另外,我只是切换到用单引号括起来并将其保持为双引号而不是转义。它可以帮助我身后的新人。
猜你喜欢
相关资源
最近更新 更多
热门标签