如何在 jquery 中动态创建事件处理程序

How to create event handlers dynamically in jquery

我有一个可拖动的 table,我正在尝试为其拖动一个 tr,我想将它放到一个可放置的 table 中。 该代码按预期工作,但我想使此代码动态化。 怎么可能?这是我的代码

jQuery('#pipeline_lead_card_table_1').droppable({ 
   tolerance: 'pointer',
   drop: function(event, ui) {   
    jQuery('#pipeline_lead_card_table_1 .pipeline_lead_card_table      
    tbody').append(ui.helper.children());
  }
}); 

jQuery('#pipeline_lead_card_table_2').droppable({ 
  tolerance: 'pointer',
  drop: function(event, ui) {   
    jQuery('#pipeline_lead_card_table_2 .pipeline_lead_card_table    
    tbody').append(ui.helper.children());
  }
}); 

jQuery('#pipeline_lead_card_table_3').droppable({ 
  tolerance: 'pointer',
  drop: function(event, ui) {   
    jQuery('#pipeline_lead_card_table_3 .pipeline_lead_card_table 
      body').append(ui.helper.children());
     }
  }); 

 jQuery('#pipeline_lead_card_table_4').droppable({ 
   tolerance: 'pointer',
   drop: function(event, ui) {   
     jQuery('#pipeline_lead_card_table_4 .pipeline_lead_card_table     
       tbody').append(ui.helper.children());
      }
  }); 

我想让这段代码动态化,因为我不知道会动态生成多少 table。

扩展我的评论,您可以像这样简化代码:

(function($) {

  function makeDrop($o) {
    $o.droppable({
      tolorance: "pointer",
      drop: function(e, ui) {
        $(".pipeline_lead_card_table tbody", this).append(ui.helper.children());
      }
    });
  }

  makeDrop($('#pipeline_lead_card_table_1'));
  makeDrop($('#pipeline_lead_card_table_2'));
  makeDrop($('#pipeline_lead_card_table_3'));
  makeDrop($('#pipeline_lead_card_table_4'));
})(jQuery);

不,如果您的每个表都有一个 Class 属性,例如:can-change,您可以进一步简化代码:

(function($) {

  function makeDrop($o) {
    $o.droppable({
      tolorance: "pointer",
      drop: function(e, ui) {
        $(".pipeline_lead_card_table tbody", this).append(ui.helper.children());
      }
    });
  }

  makeDrop($('.can-change'));
})(jQuery);