No onclick event for jQuery element added after initial page load

时间:2015-06-15 14:37:03

标签: jquery ruby-on-rails nested-forms

In our rails app, we have a table where each tbody row is a nested field. I want to limit nested fields based on current field count. To do so, I am following this guide provided by the nested_form docs.

To better suit our app, I modified the code below.

// app/views/users/index.html.haml
:javascript
  $(function() { limitNestedFields('#{@tenant.max_users}'); })

// app/assets/javascripts/limit_nested_fields.js
function limitNestedFields(limitingFactor) {
  var fieldsCount = $('tr.fields').length,
      maxFieldsCount = limitingFactor,
      $addLink = $('.add_nested_fields');
  function toggleAddLink() {
    $addLink.toggle(fieldsCount <= maxFieldsCount)
  }
  $addLink.click(function() {
    console.log("ADDING FIELD");
    if(fieldsCount < limitingFactor){
      fieldsCount += 1;
    }
    toggleAddLink();
  });
  $('.remove_nested_field').click(function() {
    console.log("REMOVING FIELD");
    fieldsCount -= 1;
    toggleAddLink();
  });
  toggleAddLink();
}

When inserting console statements, I am able to see that clicking $addLink works as expected. When I reach limitingFactor number of tbody rows, $addLink button disappears. However, I only receive log statements if I click $('.remove_nested_field') if it was present on page load.

This is important, because say a tenant may only have 10 users, and currently has 6. Say they add 4 rows of nested fields (4 users) BEFORE hitting Update. The "Add User" button ($addLink) will toggle hide. If they incorrectly fill in a nested field and wish to delete one ($('.remove_nested_field')), then the "Add User" will only appear if they click one of the original 6 rows before adding.

1 个答案:

答案 0 :(得分:2)

尝试替换

$('<selector>').click(function() {

$(document).delegate('<selector>', 'click', function() {

这应该在最初运行此脚本后添加的元素上触发。

说明: 当您执行.click时,您将事件添加到已知的特定元素列表中。如果您添加新元素,他们就不会拥有该事件,即使它们与该选择器匹配也是如此。

使用.delegate,您将事件放在整个DOM(也称为文档)上,然后说出&#34;当我们点击一​​下时,看看它是否在这个选择器上,如果有,请执行此操作和&#34; #34 ;.因为选择器检查在点击之后发生,它包括自那以后添加的那些。

函数.on有一个类似的模式,应该使用更多现代版本的jquery来代替委托:http://api.jquery.com/delegate/