jQuery - 克隆表单元素并更改标签

时间:2016-03-28 15:46:02

标签: javascript jquery html dom

我遇到了问题 - 我想克隆HTML表单的一部分,但我不知道如何更改标签for属性。

我正在使用这样的代码:

<script>

    $('#add-service').click(function () {
        $('.services div.service:last').clone(true)
        .find(':input').each(function () {
            this.name = this.name.replace(/\[(\d+)\]/, function (str, p1) {
                return '[' + (parseInt(p1, 10) + 1) + ']';
            })

            this.id = this.name

        }).end().find('label').each(function () {
            $(this).css('background-color','red');
            $(this).attr('for', function (index, old) {
                old.replace(/\[(\d+)\]/, function (str, p1) {
                    return '[' + (parseInt(p1, 10) + 1) + ']';
                });
            })
        }).end().insertAfter('.services div.service:last');
    });

</script>

for的{​​{1}}属性未更新(但label是)

Working fiddle

问题:

  1. 如何更新上述代码以使标签background-color也更新
  2. 是否可以重写此代码以缩短

2 个答案:

答案 0 :(得分:3)

你说得对,但你错过了一个回复陈述。

$(this).attr('for', function (index, old) {
    return old.replace(/\[(\d+)\]/, function (str, p1) {
        return '[' + (parseInt(p1, 10) + 1) + ']';
    });
})

请记住,您有2个嵌套函数,每个返回仅适用于您当前所在的函数。

答案 1 :(得分:2)

运行replace后需要返回新值。

$(this).attr('for', function (index, old) {
  return old.replace(/\[(\d+)\]/, function (str, p1) {
    return '[' + (parseInt(p1, 10) + 1) + ']';
  });
})
相关问题