for循环不使用innerHTML

时间:2014-01-10 10:44:39

标签: javascript for-loop innerhtml

我有一个包含innerHTML的for循环,我无法弄清楚它为什么不起作用。代码如下:

<head>
<script language="javascript">

function afterload()
{ 
    for(var n=1; n<11; n++)
    {
        document.getElementById("item"+n).innerHTML = window.opener.document.getElementById("item"+n).value;
        document.getElementById("prc"+n).innerHTML = window.opener.document.getElementById("prc"+n).value;
        document.getElementById("qty"+n).innerHTML = window.opener.document.getElementById("qty"+n).value;
        document.getElementById("amt"+n).innerHTML = window.opener.document.getElementById("totl"+n).value;
    } 
}
</script>
</head>

<body onload="afterload()">
</body>

在正文中有表格数据,上面的ID为item1prc1qty1amt1,它们最多可以运行10.父窗口也有使用上面的id输入字段,它们也运行到10.最令人困惑的是,如果我删除for循环并写入字段的实际ID,它就可以完美地工作。

2 个答案:

答案 0 :(得分:0)

<head>
<script language="javascript">

function afterload()
{ 
var item = document.getElementById("item");
var itemvalue = document.getElementById("item").value;
var prc = document.getElementById("prc");
var prcvalue = document.getElementById("prc").value;
var qty = document.getElementById("qty");
var qtyvalue = document.getElementById("qty").value;
var amt = document.getElementById("amt");
var amtvalue = document.getElementById("totl").value;
    for(var n=1; n<11; n++)
    {
       item.innerHTML += (itemvalue + "*" + n + "=" + (itemvalue*n) + "<br />");
       prc.innerHTML += (prcvalue + "*" + n + "=" + (prcvalue*n) + "<br />");
       qty.innerHTML += (qtyvalue + "*" + n + "=" + (qtyvalue*n) + "<br />");
       amt.innerHTML += (amtvalue + "*" + n + "=" + (amtvalue*n) + "<br />");
    } 
}
</script>
</head>

<body onload="afterload()">
</body>

答案 1 :(得分:0)

function innerHtml(n)
{
        document.getElementById("item"+n).innerHTML =   window.opener.document.getElementById("item"+n).value;
        document.getElementById("prc"+n).innerHTML = window.opener.document.getElementById("prc"+n).value;
        document.getElementById("qty"+n).innerHTML = window.opener.document.getElementById("qty"+n).value;
        document.getElementById("amt"+n).innerHTML = window.opener.document.getElementById("totl"+n).value;
}

function afterload()
{ 
    for(var n=1; n<11; n++)
    {
       innerHtml(n);
    } 
}

希望有所帮助!