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

时间:2018-07-26 13:54:48

标签: jquery jquery-ui jquery-ui-draggable jquery-ui-droppable

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

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());
      }
  }); 

我想使此代码动态化,因为我不知道将动态生成多少张表。

1 个答案:

答案 0 :(得分:0)

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

(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);