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

那在我的<head>部分,我用这个来称呼它。

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

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

有什么想法吗?

4

1 回答 1

0

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

创建图像标签时需要转义双引号。

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

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);
}
于 2013-02-19T15:56:01.957 回答