【问题标题】:Add number to increment value of id attribute with cloned jQuery object使用克隆的 jQuery 对象将数字添加到 id 属性的增量值
【发布时间】:2012-06-04 11:25:28
【问题描述】:

我正在使用 jQuery 1.7.2 克隆一组表单输入元素。每个输入元素都有一个 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”问题。

谁能看到失败的地方并提出修复建议?

谢谢各位!

【问题讨论】:

  • 你点击的a标签有ID,我认为没有
  • 没有。我认为 $(this).attr('id') 在这种情况下会得到克隆中输入的 id,而不是被点击的 a 标签的 id。如何将numberOfAdditionalAuthors 附加到所有克隆输入标签的 id 属性?

标签: jquery clone


【解决方案1】:

您对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;
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-21
    • 2017-09-11
    • 2015-03-17
    • 2016-03-13
    • 2011-12-22
    • 1970-01-01
    • 2016-08-05
    • 2013-11-03
    相关资源
    最近更新 更多