如何动态添加文本框而不丢失先前文本框的值? [英] how to add text boxes dynamically without losing values of previous textboxes?

查看:101
本文介绍了如何动态添加文本框而不丢失先前文本框的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用innerHTML动态添加文本框.代码示例如下:

<html>
<head>
  <script type="text/javascript" >
  var i=0;
  function add()
  {
    var tag = "<input type='text' name='" + i + "' /> <br/>";
    document.getElementById("y").innerHTML += tag;
    i++;
  }
  </script>
</head>

<body>
  <input type="button" id="x" value="Add" onclick="add();" />
  <div id="y"></div>
</body>

</html

是否有任何方法可以动态添加文本框,而不会在添加新文本框时丢失前一个文本框的值?
类似的问题已经发布,但是没有答案:(

在这种情况下我想添加文本框怎么办?

function add() {
   var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '"  class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
   document.getElementById("addskills").innerHTML += element;
   i++;
}

解决方案

是的,通过DOM操作:

function add() {
    var tag = document.createElement('input'); // Create a `input` element,
    tag.setAttribute('type', 'text');          // Set it's `type` attribute,
    tag.setAttribute('name', i);               // Set it's `name` attribute,

    var br = document.createElement('br');     // Create a `br` element,

    var y = document.getElementById("y");      // "Get" the `y` element,
    y.appendChild(tag);                        // Append the input to `y`,
    y.appendChild(br);                         // Append the br to `y`.
    i++;
}

这不会像innerHTML那样触发浏览器的DOM解析器,而一切保持不变.

(innerHTML强制浏览器重新解析整个DOM,因为可以使用innerHTML添加任何内容,因此与向节点添加元素相反,浏览器无法预测任何内容.)

现在,添加此内容:

<li class="ie7fix" style="width:620px;">
    <div class="m_elementwrapper" style="float:left;">
        <label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4">
            <span>
                <span class="pspan arial" style="text-align:right;font-size:14px;">
                    <span class="ispan" xml:space="preserve">
                    </span>
                </span>
            </span>
        </label>
        <div style="float:left;width:475px;" class="m_elementwrapper">
            <input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '"  class="fieldcontent">
            <div class="fielderror">
            </div>
        </div>
    </div>
    <div style="clear:both;font-size:0;">
    </div>
</li>

您需要:

function add() {
    // Create elements
    var d1 = c('div'),  s1 = c('span'), ip = c('input'),
        d2 = c('div'),  s2 = c('span'), li = c('li'),
        d3 = c('div'),  s3 = c('span'), la = c('label'),
        d4 = c('div');
    // You can "chain" `appendChild`.
    // `li.appendChild(d1).appendChild(la);` is the same as `li.appendChild(d1); d1.appendChild(la);`
    li.appendChild(d1).appendChild(la).appendChild(s1).appendChild(s2).appendChild(s3);
    d1.appendChild(d2).appendChild(ip);
    d2.appendChild(d3);
    li.appendChild(d4);

    setAttributes(
        [li, d1, la, s2, s3, d2, ip, d3, d4],
        [
            {'class':"ie7fix",              'style':"width:620px;"  },
            {'class':"m_elementwrapper",    'style':"float:left;"   },
            {'class':"fieldlabel",          'style':"width:106px;float:left;padding-top:3px;", 'for':"p1f4" },
            {'class':"pspan arial",         'style':"text-align:right;font-size:14px;"  },
            {'class':"ispan",               'xml:space':"preserve"  },
            {'class':"m_elementwrapper",    'style':"float:left;width:475px;"   },
            {'class':"fieldcontent",        'type':"text",      'style':"font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;", 'name':''+i},
            {'class':"fielderror"   },
            {'style':"clear:both;font-size:0;"  }
        ]
    );
    var br = document.createElement('br');     // Create a `br` element,
    var y = document.getElementById("y");      // "Get" the `y` element,
    y.appendChild(li);                         // Append the input to `y`,
    y.appendChild(br);                         // Append the br to `y`.
    i++;
}

// Apply a array of attributes objects {key:value,key:value} to a array of DOM elements.
function setAttributes(elements, attributes){
    var el = elements.length,
        al = attributes.length;
    if(el === al){
        for(var n = 0; n < el; n++){
            var e = elements[n],
                a = attributes[n];
            for(var key in a){
                e.setAttribute(key, a[key]);
            }
        }
    }else{
        console.error("Elements length " + el + " does not match Attributes length " + al);
    }
}

// Alias for shorter code.
function c(type){
    return document.createElement(type);
};

i am using innerHTML to add text boxes dynamically. The code sample is as follows:

<html>
<head>
  <script type="text/javascript" >
  var i=0;
  function add()
  {
    var tag = "<input type='text' name='" + i + "' /> <br/>";
    document.getElementById("y").innerHTML += tag;
    i++;
  }
  </script>
</head>

<body>
  <input type="button" id="x" value="Add" onclick="add();" />
  <div id="y"></div>
</body>

</html

Are there any ways to add text boxes dynamically without losing values of previous text box when a new text box is added?
Similar question has been posted, but there are no answers :(

What if I want to add textbox in this situation:

function add() {
   var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '"  class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
   document.getElementById("addskills").innerHTML += element;
   i++;
}

解决方案

Yes, through DOM Manipulation:

function add() {
    var tag = document.createElement('input'); // Create a `input` element,
    tag.setAttribute('type', 'text');          // Set it's `type` attribute,
    tag.setAttribute('name', i);               // Set it's `name` attribute,

    var br = document.createElement('br');     // Create a `br` element,

    var y = document.getElementById("y");      // "Get" the `y` element,
    y.appendChild(tag);                        // Append the input to `y`,
    y.appendChild(br);                         // Append the br to `y`.
    i++;
}

This doesn't trigger the browser's DOM parser like a innerHTML does, leaving everything intact.

(innerHTML forces the browser to re-parse the entire DOM, because anything could be added with innerHTML, so the browser can't predict anything, in contrast to adding a node to a element.)

Now, to add this:

<li class="ie7fix" style="width:620px;">
    <div class="m_elementwrapper" style="float:left;">
        <label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4">
            <span>
                <span class="pspan arial" style="text-align:right;font-size:14px;">
                    <span class="ispan" xml:space="preserve">
                    </span>
                </span>
            </span>
        </label>
        <div style="float:left;width:475px;" class="m_elementwrapper">
            <input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '"  class="fieldcontent">
            <div class="fielderror">
            </div>
        </div>
    </div>
    <div style="clear:both;font-size:0;">
    </div>
</li>

You'll need:

function add() {
    // Create elements
    var d1 = c('div'),  s1 = c('span'), ip = c('input'),
        d2 = c('div'),  s2 = c('span'), li = c('li'),
        d3 = c('div'),  s3 = c('span'), la = c('label'),
        d4 = c('div');
    // You can "chain" `appendChild`.
    // `li.appendChild(d1).appendChild(la);` is the same as `li.appendChild(d1); d1.appendChild(la);`
    li.appendChild(d1).appendChild(la).appendChild(s1).appendChild(s2).appendChild(s3);
    d1.appendChild(d2).appendChild(ip);
    d2.appendChild(d3);
    li.appendChild(d4);

    setAttributes(
        [li, d1, la, s2, s3, d2, ip, d3, d4],
        [
            {'class':"ie7fix",              'style':"width:620px;"  },
            {'class':"m_elementwrapper",    'style':"float:left;"   },
            {'class':"fieldlabel",          'style':"width:106px;float:left;padding-top:3px;", 'for':"p1f4" },
            {'class':"pspan arial",         'style':"text-align:right;font-size:14px;"  },
            {'class':"ispan",               'xml:space':"preserve"  },
            {'class':"m_elementwrapper",    'style':"float:left;width:475px;"   },
            {'class':"fieldcontent",        'type':"text",      'style':"font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;", 'name':''+i},
            {'class':"fielderror"   },
            {'style':"clear:both;font-size:0;"  }
        ]
    );
    var br = document.createElement('br');     // Create a `br` element,
    var y = document.getElementById("y");      // "Get" the `y` element,
    y.appendChild(li);                         // Append the input to `y`,
    y.appendChild(br);                         // Append the br to `y`.
    i++;
}

// Apply a array of attributes objects {key:value,key:value} to a array of DOM elements.
function setAttributes(elements, attributes){
    var el = elements.length,
        al = attributes.length;
    if(el === al){
        for(var n = 0; n < el; n++){
            var e = elements[n],
                a = attributes[n];
            for(var key in a){
                e.setAttribute(key, a[key]);
            }
        }
    }else{
        console.error("Elements length " + el + " does not match Attributes length " + al);
    }
}

// Alias for shorter code.
function c(type){
    return document.createElement(type);
};

这篇关于如何动态添加文本框而不丢失先前文本框的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆