jquery、克隆问题和保持唯一ID!

jquery、克隆问题和保持唯一ID!,jquery,Jquery,我决定使用jquery来创建下拉菜单的副本,而不是使用我的perl脚本。我有一个问题 我有一系列的下拉框,可以多次克隆。结构如下: <div id="org_dropmenus_asdf"> <table border="0"> <tr> <td valign="top"> <select name="wimpy_asdf_1" id="wimpy_asdf_1" size="4">

我决定使用jquery来创建下拉菜单的副本,而不是使用我的perl脚本。我有一个问题

我有一系列的下拉框,可以多次克隆。结构如下:

<div id="org_dropmenus_asdf">
    <table border="0">
    <tr>
    <td valign="top">
        <select name="wimpy_asdf_1" id="wimpy_asdf_1" size="4">
          <option value='1'>1</option>
          <option value='2'>2</option>
        </select>;
    </td>
    <td valign="top">
        <select name="monkey_asdf_1" id="monkey_asdf_1" size="4">
          <option value='c'>c</option>
          <option value='d'>d</option>
        </select>;    
    </td>
            </tr>
            </table><p>
    </div>|;

1.
2.
;
C
D
;    

|;
我克隆变量$cloneDiv=$('#org_dropmenus_asdf').clone()


如何搜索和替换asdf_1(“1”)并用新值递增?

您需要按照以下步骤进行操作:

var counter = 1;
$cloneDiv = $('#org_dropmenus_asdf').clone().find('[id]').attr('id', function(idx, oldId){
    return oldId.substr(0, -1) + counter;
}).attr('name', function (idx, oldName) {
    return oldName.substr(0, -1) + counter;
});
您可以重复执行此操作,每次递增
计数器
。请注意,此代码最多只能使用9个字符,因为它会删除最后一个字符;超过10个字符需要删除更多字符

还请注意,这不会更改
org\u dropmenus\u asdf
id属性,对于有效的DOM,也需要更改该属性

function incrementId(idString) {

    // split it at the underscore
    var pieces = idString.split("_");

    // if there is a fourth element, then it just needs incrementing
    if (pieces[3]) {
        pieces[3] = parseInt(pieces[3]) + 1;

    // if not, then it needs to be added
    } else {
        pieces[3] = "1";
    }

    // reconstruct the ID by joining with the underscore character
    return pieces.join("_");
}

$cloneDiv = $('#org_dropmenus_asdf').clone();

// get the ID of the last 'org_dropmenus_asdf' div and increment
var lastDivId = incrementId($("div[id^=org_dropmenus_asdf]:last").attr("id"));

// get the IDs of the contained select elements, and increment
var selectIds = $("div[id^=org_dropmenus_asdf]:last select").map(function() {
    return incrementId(this.id);
}).get();

alert(lastDivId);
alert(selectIds);

部分演示+概念验证:

下面是解决此问题的另一种方法。 我使用中的id和名称作为数组,这样就可以轻松地发布到PHP并进行处理,而无需花费太多精力。 这将两个字段名绑定到我可以在发布时链接它们。它是一个选择和一个文本字段。 这发生在我附加了一个克隆之后

var newid = Number($('.table_id').last().find(':text').attr('id').substr(-2,1)) + 1;

$('.table_id').last().find(':text').attr('id','detailValue['+newid+']').attr('name','detailValue['+newid+']');
$('.table_id').last().find(':select').attr('id','detailValue['+newid+']').attr('name','detailValue['+newid+']');

如何访问级别上的ID?这会找到包括select标记在内的所有ID吗?