Jquery如何将值id从一个事件处理程序传递给另一个

问题描述

我有一个 add-row 按钮。点击它后,我会在 datatable添加一行。

$('.add-row').on('click',function() {
            id = 0;
            name = $('#name').val();
            email = $('#email').val();
            cno = $('#cno').val();
            bdy = $('#bday').val();
            
            t.row.add([
                name,email,cno,bdy,'<button class ="btn btn-danger del">Delete</button>' + '' + '<button class="btn btn-warning upd" data-id="'+$('#example').DataTable().rows().count()+'">Edit</button>'





            ]).draw(false);
            $("#name").val('');
            $("#email").val('');
            $("#cno").val('');
            $("#bday").val('');

        });

在上面的代码中,我使用了 data-id 并向其添加row id。在我的 edit 按钮上点击我得到 data-id 值。

$("body").on("click",".upd",function(e) {
            const id = $(this).attr("data-id");
            console.log(id);
            // Prevent event propagation
            e.stopPropagation();
            var $row = $(this).closest('tr');
            var data = t.row($row).data();

            //alert('Edit ' + data[0]);
             name = data[0];
             email = data[1];
             cno = data[2];
             bdy = data[3];

            console.log(name);
            console.log(email);
            console.log(cno);
            console.log(bdy);

            $("#name1").val(name);
            $("#email1").val(email);
            $("#cno1").val(cno);
            $("#dob1").val(bdy);
            $("#myModal").modal('show');
            

        });

以上代码modal 获取输入数据。在我的 modal 中,我有一个 save 按钮,其 ID 为 btnsubmit。现在点击这个按钮,我想传递我的 data-id

$("#btnsubmit").on('click',function () {//in this event i want to pass the `data-id`
             
            
            var new_name = $("#name1").val();
                var new_email = $("#email1").val();
                var new_cno = $("#cno1").val();
                var new_dob = $("#dob1").val();
              
            
           
       
                $("#myModal").modal("hide");
            });

如何在其中传递 data-id 的值? 任何帮助将不胜感激。

解决方法

您可以像这样以 html 模式存储数据:

$("#myModal").data('id',id);

并使用:

var id = $("#myModal").data('id');