使用jQuery克隆和重命名表单元素 [英] Cloning and renaming form elements with jQuery

查看:99
本文介绍了使用jQuery克隆和重命名表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种克隆/重命名或重新创建地址字段的有效方法,以提供在同一页面上提交多个地址的功能.因此,使用这样的表单示例:

I am looking for an effective way to either clone/rename or re-create address fields to offer ability to submit multiple addresses on the same page. So with form example like this:

<div id="addresses">
  <div class="address">
    <input type="text" name="address[0].street">
    <input type="text" name="address[0].city">
    <input type="text" name="address[0].zip">
    <input type="text" name="address[0].state">
  </div>
</div>
<a href="" id="add_address">Add address form</a>

据我了解,有两种方法可以做到这一点:

From what I can understand there are two options to do that:

  1. 逐个字段重新创建表单并增加索引,这很冗长:

  1. Recreate the form field by field and increment the index which is kind of verbose:

var index = $(".address").length;

$('<`input`>').attr({
name: 'address[' + index + '].street',
type: 'text'
}).appendTo(...);

$('<`input`>').attr({
name: 'address[' + index + '].city',
type: 'text'
}).appendTo(...);

$('<`input`>').attr({
name: 'address[' + index + '].zip',
type: 'text'
}).appendTo(...);

$('<`input`>').attr({
name: 'address[' + index + '].state',
type: 'text'
}).appendTo(...);

  • 克隆现有层并替换克隆中的名称:

  • Clone Existing layer and replace the name in the clone:

    $("div.address").clone().appendTo($("#addresses"));
    

  • 您建议使用哪一种来提高效率,如果能使其排名第二,请提出建议,我将如何进行搜索并将所有出现的[0]替换为[1]([n]).谢谢.

    Which one do you recommend using in terms of being more efficient and if its #2 can you please suggest how I would go about search and replacing all occurrences of [0] with [1] ([n]). Thank you.

    推荐答案

    理论上,最简单的方法是克隆然后更改名称:

    In theory, the simplest way would be to clone then change name:

    var newaddress= $("#addresses div.address").eq(0).clone();
    newaddress.find('input').each(function() {
        this.name= this.name.replace('[0]', '['+i+']');
    });
    $('#addresses').append(newaddress);
    

    但是:

    a. jQuery的clone()是一件非常讨厌的工作.在IE上,它将节点序列化为HTML,使用正则表达式(!)处理HTML字符串以删除其bodge-job内部ID属性,然后要求浏览器重新解析它.这是jQuery中我最不喜欢的部分之一:它很容易出错,会丢失一些信息,而且速度很慢(速度对于您在这里似乎做的很小的事情并不重要).

    a. jQuery's clone() is a really nasty piece of work. On IE, it serialises the nodes to HTML, processes the HTML string with regex (!) to remove its bodge-job internal ID attributes and then asks the browser to re-parse it. This is one of my least favourite parts of jQuery: it's highly error-prone, loses some information, and is slow (not that speed matters for the quite small job you seem to be doing here).

    浏览器的本机cloneNode(true)方法要好得多,但是如果您正在做jQuery的东西,则不能真正使用它,因为它会复制jQuery的内部ID,从而可能混淆其脚本.啊.真是一团糟.

    The browser's native cloneNode(true) method is much better, but you can't really use it if you're doing jQuery stuff because it will copy jQuery's internal ids, potentially confusing its scripting. Ugh. What a mess.

    b.当您更改输入的名称时,无论是在此处使用input.name还是在示例中使用attr(),都将在IE< = 7中出现问题.

    b. When you change an input's name, whether that's by input.name as here or using attr() as in your example, there are issues in IE<=7.

    尤其是,尽管它将使用正确的控件名称提交输入,但它们不会在form.elements HTMLCollection中(或在form本身上)以正确的名称建立索引,尽管无论如何您都不应使用它).如果您要基于ID或jQuery选择器而不是老式的HTMLCollection接口来选择输入,那么这不一定是问题.更糟糕的是,如果您使用单选按钮,则不会正确地对它们进行名称分组.

    In particular, though it will submit the inputs with the correct control name, they won't be indexed under the right name in the form.elements HTMLCollection (or on form itself, though you shouldn't use that anyway). This isn't necessarily a problem if you are selecting inputs based on IDs or jQuery selectors rather than the old-school HTMLCollection interface. Worse is that radio buttons, if you use any, won't be properly name-grouped.

    如果这是您的问题,恐怕只能使用innerHTML/html()来创建div(如pst的回答所示),这是您唯一的选择. (您始终可以将两者结合起来,使用HTML创建,然后使用text()attr()val()等更改其他属性和文本内容,以避免在将文本字符串粘贴到HTML时避免常见的HTML转义问题. )

    If this is a concern for you I'm afraid using innerHTML/html() to create the div, as in pst's answer, is your only option. (You can always combine the two, creating using HTML then changing the other attributes and text content using text(), attr(), val() etc. to avoid the usual HTML-escaping problems when you go around sticking text strings into HTML.)

    这篇关于使用jQuery克隆和重命名表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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