使用克隆的jQuery对象添加数字以增加id属性的值

时间:2012-06-04 11:25:28

标签: jquery clone

我使用jQuery 1.7.2克隆一组表单输入元素。每个input元素都有一个id属性。我希望克隆元素使用与源元素相同的id属性,但附加一个数字以使它们唯一。

我的代码是:

    // Add additional author fields
    jQuery('#addanotherauthor a').click(function () {
        // Clone 'other author' group of fields
        var markUpToClone = jQuery('.other-authors').clone();
        // Set all input values of cloned mark-up to empty, remove 'disabled' attribute
        markUpToClone.find('input').val('').removeAttr('disabled');
        // Ensure cloned inputs have unique id attributes
        var numberOfAdditionalAuthors = $('.other-authors').length.toString();
        markUpToClone.find('input').attr('id', $(this).attr('id') + numberOfAdditionalAuthors);
        // Append emptied clone
        jQuery('#otherauthorscontainer').append(markUpToClone);
        return false;
    });

当我运行它时,克隆元素的id属性变为“undefined1',' undefined2'有趣的是,如果我这样做:

markUpToClone.find('input').attr('id', numberOfAdditionalAuthors);

它返回正确递增数字的id。如果我这样做:

markUpToClone.find('input').attr('id', $(this).attr('id'));

它返回与源值相同的id。但是当我试着将两者放在一起时:

markUpToClone.find('input').attr('id', $(this).attr('id') + numberOfAdditionalAuthors);

我得到了'undefined1'问题

任何人都可以看到失败的地方并提出修复建议吗?

谢谢大家!

1 个答案:

答案 0 :(得分:2)

您对this的使用脱离了背景。我使用attr(function(index, attr){})来管理ID的

// Add additional author fields
    jQuery('#addanotherauthor a').click(function () {
        // Clone 'other author' group of fields
        var markUpToClone = jQuery('.other-authors').clone();
        // Set all input values of cloned mark-up to empty, remove 'disabled' attribute
        var numberOfAdditionalAuthors = $('.other-authors').length/*.toString()*/;// toString() not needed
        markUpToClone.find('input').val('').removeAttr('disabled')
        // Ensure cloned inputs have unique id attributes
                .attr('id', function(i, id){
                        return id + numberOfAdditionalAuthors;
                });


        // Append emptied clone
        jQuery('#otherauthorscontainer').append(markUpToClone);
        return false;
    });