JavaScript清除文本框DOM只清除顶部框

时间:2016-02-05 10:12:40

标签: javascript html html5 button submit

所以我有一组文本框,我有一个清晰的按钮,但是当点击它时,它只从顶部框中删除文本。我想知道是否有办法以这种方式移除所有盒子?

function eraseText() {
    document.getElementById("output").value = "";
}


var sections = {

  p1 : {sname: "Dynamic Table   ", mscore: 20},
  p2 : {sname: "IntelliJ Usage  ", mscore: 10},
  p3 : {sname: "Calender Control", mscore: 30},
  p4 : {sname: "Active Form     ", mscore: 20},
  p5 : {sname: "Object Database ", mscore: 20}
};

document.write("<pre>");
document.write(Object.keys(sections).reduce(function(s, p, i) {
   var o = sections[p];
   return s + (i>0?'<br><br><br><br>':'') + o.sname +  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + o.mscore + '&nbsp;&nbsp;&nbsp;' + '<textarea id="output" rows="4" cols="25">' + '</textarea>' + '&nbsp;&nbsp;&nbsp;'}, '')
);
document.write("</pre>");

然后在HTML中我有这个提交按钮:

 <input type="button" value="Clear" onclick="javascript:eraseText();"> 

1 个答案:

答案 0 :(得分:3)

如果您将其全部包装在表单标签中,则可以使用

<input type="reset" /> 

如果没有,我会给他们一个课程并编码:

function eraseText() {
    var out = document.querySelectorAll(".out");
    for (var i=0;i<out.length;i++) {
      out[i].value="";
    }
}

查看代码我还会更改document.write的使用并删除无用的javascript:标签

var sections = {
  p1 : {sname: "Dynamic Table   ", mscore: 20},
  p2 : {sname: "IntelliJ Usage  ", mscore: 10},
  p3 : {sname: "Calender Control", mscore: 30},
  p4 : {sname: "Active Form     ", mscore: 20},
  p5 : {sname: "Object Database ", mscore: 20}
};

document.getElementById("container").innerHTML=Object.keys(sections).reduce(
  function(s, p, i) {
   var o = sections[p];
   return s + (i>0?'<br><br><br><br>':'') + o.sname + 
    '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + 
    o.mscore + '&nbsp;&nbsp;&nbsp;' + 
    '<textarea class="out" id="output" rows="4" cols="25"></textarea>' + '&nbsp;&nbsp;&nbsp;'
  }, '');

并为容器提供

的CSS
#container {
    display: block;
    unicode-bidi: embed;
    font-family: monospace;
    white-space: pre;
}