【问题标题】:How to use getElementById and innerHTML correctly (.append() )如何正确使用 getElementById 和 innerHTML (.append() )
【发布时间】:2014-06-25 15:20:15
【问题描述】:

我面临以下问题:

我有一个用户输入表单,在提交时会调用函数 drawmycolor()。然后该函数会给出一个表格,显示通过用户输入的数字生成的颜色。所有这些都正常工作,唯一的问题是表格没有显示在网站上,而是显示在一个新窗口中。我试图通过在 html 部分中打开一个 div 元素,然后使用 getElementById 引用该 div,然后将带有 innerHTML 的表放入 div 元素来解决这个问题。这是我的代码:

 function drawmycolor()
 {
 a = Number(document.color.d.value); //getting the user input from the form
 b = Number(document.color.e.value);
 c = Number(document.color.f.value);

 if (a >= 0 && a < 255 && Math.floor(a) == a &&
     b >= 0 && b < 255 && Math.floor(b) == b &&
     c >= 0 && c < 255 && Math.floor(c) == c)


    {
       mycolor = "#" + getHexadecimalValue(a) + 
        ""  + getHexadecimalValue(b) +
        ""  + getHexadecimalValue(c); 
 var div = document.getElementById('ausgabe');  //Here I am referencing the div-el.
 div.innerHTML = div.innerHTML + "...." //here i don't know how to put in the table below.
       document.write('<br><table border="1" cellspacing="1"cellpadding="1">');
       document.write('<tr><th>Hexadecimal Red</th><th>' +
       'Hexadecimal Green</th><th>' +
       'Hexadecimal Blue</th><th>' +
       'Color</th></tr>');
       document.write('<tr><td>' + getHexadecimalValue(a) + '</td><td>' + 
       getHexadecimalValue(b) + '</td><td>' + 
       getHexadecimalValue(c) +                            
       '</td><td bgcolor="mycolor"</td></tr>'); //RIGHT HERE I WANT TO SET THE COLOR
   document.write('</table>');
 }
 else
 ..

 <div id="ausgabe"><br> Blubb </div> //this is the div-element where the output is 
                                       supposed to be...

如果您能在此问题上提供任何帮助,我将不胜感激 - 提前感谢您! :)

【问题讨论】:

    标签: javascript html append innerhtml getelementbyid


    【解决方案1】:

    每次调用 document.write("something") 时,它都会用 "something" 覆盖之前的内容。正如昆汀所指出的那样:

     var div = document.getElementById('ausgabe'); 
    
    
    
    div.innerHTML="Your entire table related code here";
    

    (如果您不想要该 div 的先前内容,则不需要 div.innerHTML=div.innerHTML+....)。

    或者你可以这样做(如果你想追加一个新的 div):

    var dNew = document.createElement('div');
    dNew.innerHTML="yolur table related content here"
    document.getElementById('your outer div id here').appendChild(dNew);
    

    【讨论】:

    • 谢谢 - 它成功了!这实际上是我之前尝试过的,但我仍然有 document.write(..) 符号。一旦我删除了这些,只像你说的那样输入表格代码,它就起作用了..太棒了:)
    【解决方案2】:

    "..... // 替换为您输入的字符串document.write

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多