如何将JS应用于用户在表格中添加的行

How to apply JS to user added rows in tabel

本文关键字:表格 添加 用户 JS 应用于      更新时间:2023-09-26

>我正在使用rails生成一个表单,允许用户单击按钮向表格添加新行。截至目前,用户可以单击添加按钮并出现一个新行。

我遇到的麻烦是使用自动数字来掩盖百分比值的列。JS 不会应用于用户动态创建的列。我正在使用类,所以我很困惑为什么在用户添加新行时没有将自动数字掩码应用于新行。"百分比"类正在处理窗体的其他部分。

# JS
$(function() {
  $('.percentage').autoNumeric('init', {aSign: '%', pSign: 's'});
});
# the field is set to the proper class
<tr class="fields">
    <td><input class="percentage" placeholder="Equity %" type="text"></td>
</tr>
# link that adds a new row
<a class="add_nested_fields" data-association="business_contacts" data-blueprint-id="business_contacts_fields_blueprint" data-target="#business_contacts" href="javascript:void(0)">Add a field</a>

添加的每一行上都有 class="fields"。我尝试过JS的onClick,但没有成功的结果。

当你的 JS 在页面加载后运行时,autoNumeric 被调用到目前存在的所有 DOM 元素上.percent类。但是,当您添加新行时,您需要再次调用autoNumeric。例如:

    Function addRow(){       $.('.container').append(this.$row);      $.('.percent').autoNumeric();}
Or you can share ur js code so I can help better.
 $.('.add_nested_fields').click(function()$.('.percent').autoNumeric();})

编辑:提问者找到的解决方案@Questifier

  $(function() {  $(document).on('nested:fieldAdded', function(event){    $('.percentage').autoNumeric('init', {aSign: '%', pSign: 's'});  })});

完美工作。在您问我之后,我阅读了更多关于宝石的信息。复制该代码并使其成为您的答案,如果您愿意 - 感谢您的帮助。