jQuery 我的输入不适用于新调用的元素

jQuery my enter doesn't work on new called elements

当 jQuery 生成新字段时,新字段不适用于 'enter'。

这是我的脚本:

咖啡

$('.teaser-form').keyup (e) ->
  if e.keyCode == 13
    $('.add-new-list').click()

form.haml

= f.simple_fields_for :products do |p|
  = render 'product_fields', :f => p 
.gear-item-add
  = link_to_add_association 'add item', f, :gears, class: "btn btn-default add-new-list"

因此 jQuery 调用 link_to_add_association 按钮创建如下所示的字段。 (第一个字段是初始字段,所以如果我按回车键,则会生成第二个字段和第三个字段...但是如果我尝试继续第三个字段并按回车键,则没有任何反应)

_product_field.haml

.nested-fields.gear-patrol
  .col-md-12
    = f.text_field :list, class: 'teaser-form form-control', placeholder: 'testing'

将事件处理程序添加到 新创建的元素

重新执行这段代码。

$('.teaser-form').keyup (e) ->
  if e.keyCode == 13
    $('.add-new-list').click()

或者仅将处理程序添加到新创建的元素。

当您将处理程序绑定到 class 时,它会查找所有 现有的 具有该 class 的对象并绑定逻辑——因此是新创建的对象将没有处理程序,无论它们是否具有 class。这是 .

试试这个,使用 jQuery

$('body').on('keyup', '.teaser-form', function(e) {

  if (e.keyCode == 13) {

    /* here you can put your code as:
    $('.add-new-list').click()
    */

    var _iDx = $('.teaser-form').length + 1; /*remove this line*/
    $(this).after('<input type="text" class="teaser-form" value="Field ' + _iDx + '">'); /*remove this line*/

    /*keep this code for auto focus to new element*/
    $('.teaser-form').last().focus();

  };

});
.teaser-form {
  display: block;
  padding: 4px;
  margin: 2px;
  border-radius: 4px;
  border: 1px solid #266F6F;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" class="teaser-form" value="Field 1">

希望这对您有所帮助..

当您正在寻找 CoffeeScript 和 haml 时,请在您的代码中试试这个:

$(document).on 'keyup', '.teaser-form', (e) ->
  if e.keyCode == 13
    $('.add-new-list').click()
  return

这就是它应该如何与你的代码一起工作,关于由@nnnnnn

带来的this question