Jquery 将属性中的整数替换为+;1.

Jquery 将属性中的整数替换为+;1.,jquery,coffeescript,Jquery,Coffeescript,我想向给定的Rails 4表单添加一个新的嵌套元素 咖啡脚本: ready = -> $('form').on 'click', '.add_comment', (event) -> new_fields = $(this).parent().prev('div.field').clone() new_fields.insertBefore('p.new_comment_link') event.preventDefault() $(document).

我想向给定的Rails 4表单添加一个新的嵌套元素

咖啡脚本:

ready = ->
  $('form').on 'click', '.add_comment', (event) ->
    new_fields = $(this).parent().prev('div.field').clone()
    new_fields.insertBefore('p.new_comment_link')
    event.preventDefault()

$(document).ready(ready)
$(document).on('page:load', ready)
在执行
insertBefore
之前,我想更改
new\u字段中的一些属性。
新字段的内容是:

<div class="field">
  <label for="post_comments_attributes_2_name">Name</label><br>
  <input id="post_comments_attributes_2_name" name="post[comments_attributes][2][name]" type="text">
  <input id="post_comments_attributes_2__destroy" name="post[comments_attributes][2][_destroy]" type="hidden" value="false">
  <a class="remove_category" href="#">remove</a>
</div>

名称
在不知道[2]是2的情况下,如何用+1(
[3]
)替换所有
[2]
?它可以是任何整数。

您可以使用回调函数替换()

'[1] [2]'.replace /\[(\d+)\]/g, (match, num) ->
    return "[#{parseInt(num, 10) + 1}]"
和JavaScript等价物:

'[1] [2]'.replace(/\[(\d+)\]/g, function(match, num) {
    return '[' + (parseInt(num, 10) + 1) + ']';
});

在这种情况下,您不仅需要修改输入的名称,还需要修改标签和ID,这是为了防止任何依赖于这些属性的分类的故障

咖啡脚本如下所示:

String.prototype.parseIntPlusOne = ->
  this.replace /(\d+)/, (match, num)->
    parseInt(num, 10) + 1

ready = ->
  $('form').on 'click', '.add_comment', (event) ->
    event.preventDefault()

    new_field = $(this).parent().prev('div.field').clone()

    new_field.find('label').attr 'for', (i, attr)->
      attr.parseIntPlusOne()

    new_field.find('input').attr('id', (i, attr)->
      attr.parseIntPlusOne()).attr('name', (i, attr)->
      attr.parseIntPlusOne())

    new_field.insertBefore('p.new_comment_link')

$(document).ready(ready)
$(document).on('page:load', ready)

您可以在这里查看一个工作示例:

一点OT,但是您是否考虑过在父字段上使用
数据
属性。这样你就可以克隆元素,只操作一次
attr
,而不需要多个正则表达式。我如何解决这个问题?出于好奇,#在这个字符串中做什么?@JuanMendes:string interpolation。在CoffeeScript下面编写JavaScript代码是一种更好的方法。我得到了一个
uncaughttypeerror:Object[Object Object]没有方法“replace”
错误。我尝试过:
new\u fields=$(this).parent().prev('div.field').clone().replace/\[(\d+)\]/g,(match,num)->return“[{parseInt(num,10)+1}]”
@wintermeyer:不能对jQuery对象调用
.replace()
。如果要替换其文本,请使用
.text()
@Blender:当我先使用
.text()
时,如何在以后插入它?我无法在给定的示例中运行代码。完美的解决方案。谢谢大家!-1:为什么要修改
String
的原型来添加这样一个特定的函数?