【问题标题】:For loop not working with innerHTMLFor循环不适用于innerHTML
【发布时间】:2014-01-29 07:18:49
【问题描述】:

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

<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,它会完美运行。

【问题讨论】:

  • 您是否遇到任何错误?也许您的 HTML 中没有所有元素?
  • 能否提供源数据/附加 HTML 代码以重现错误?
  • 请也提供html
  • 尝试使用转换类型“item”+String(n)。您是否在浏览器中调试过代码,您会看到发生了什么。
  • 您能提供一个我们可以检查的(非)工作样品吗?

标签: javascript for-loop innerhtml


【解决方案1】:
<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>

【讨论】:

    【解决方案2】:
    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);
        } 
    }
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2016-03-23
      • 2018-03-13
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多