茧在Rails中加载了一个新的嵌套表单后,如何执行JavaScript

How to execute JavaScript after cocoon has loaded a new nested form in Rails?

本文关键字:JavaScript 表单 何执行 嵌套 执行 加载 Rails 茧在 一个      更新时间:2023-09-26

我想设置一些字段隐藏,直到用户点击复选框,然后它们应该显示出来,并且第一次加载时效果良好,比如

$(document).ready(function(){
  $(".m100check").click(function() {
    $(this).parents('.nested-fields').children('.persrecm100').toggle();
    $(this).parents('.nested-fields').children('.bestm100').toggle();   
  });
});

但当我添加另一个嵌套表单时,该脚本将停止对给定字段的工作,仍然只对加载页面的第一个字段有效。在cocoon完成添加新的form后,我如何强制它工作?

尝试

$('#nested_rows').on('cocoon:after-insert', function(e, insertedItem){
     # your code
});

请参阅文档中的回调:https://github.com/nathanvda/cocoon

这可能不是最好的方法,但对我来说很成功:

$(document).on('ready page:load', function () {
    function set_masks () {
        $('.t0000').mask('00,00');
        $('.t000000').mask('00:00,00');
        $('.t000').mask('0,00');
    }
    function show_rec () {
        $('.checkbox').click(function () {
            $(this).closest('div.field').find('div.discip').toggle();
        });
    }

    $('#sportists').on('cocoon:after-insert', function() {
        set_masks();
        show_rec();
    });

    set_masks();
    show_rec();

    $(".add_fields").click(function() {
        set_masks();
        show_rec();
    });
});