本文介绍了我如何保留动态添加的文本框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码:

<html>
 <head>
   <title>Dynamic Form</title>
   <script type="text/javascript">
     var i = 6;
    function CreateTextbox(){
      createTextbox.innerHTML = createTextbox.innerHTML 
                   +'<input type=text name="flow'+i+'"/>'
       i++;
    }
  </script>
</head>
<body>
 <form name="form" action="post">
  <input type="button" name="what" value="clickHere" onClick="CreateTextbox()"/>
   <div id="createTextbox"></div>
 </form>
</body>

当我添加一个新的文本框时,在前一个文本框中输入的值会被删除.我怎样才能保留它?

when i add a new textbox, the value that was entered in the previous textbox is deleted. how can i retain it?

推荐答案

通过连接 innerHTML 添加 HTML 元素非常缓慢,这会导致值被清除,因为容器(div createTextbox) 并且所有子项都在每个 innerHTML 分配中重新创建.

Adding HTML element by concatenating the innerHTML is very slow and that is causing the values to be cleared, since the container (the div createTextbox) and all the childs are re-created on each innerHTML assignment.

我建议您使用 document.createElement 并使用 appendChild:

window.onload = function  () {

  var createTextbox = function () {
    var i = 6,
        container = document.getElementById('createTextbox');

    return function () {
      var div = document.createElement('div'),
          input = document.createElement('input');
      input.type= "text";
      input.name = "flow" + i;
      div.appendChild(input);
      container.appendChild(div);
      i++;
    }
  }();

  // event binding
  document.getElementById('addButton').onclick = createTextbox;
}

此处检查上述代码是否有效.

Check the above code working here.

这篇关于我如何保留动态添加的文本框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 15:15