如何通过动态创建的id从gridster.js中删除单个小部件

我需要知道如何使用gridster.add_widget通过动态创建的id删除单个gridster.js小部件。 创建的每个新窗口小部件都有一个自己的按钮来删除该单个窗口小部件,但我无法使其工作。

这是我的代码

$(document).ready(function(){ var count = 0; var newid = count + 1; $(document).on("click", "#newGrid", function() { var gridster = $(".gridster ul").gridster().data('gridster'); gridster.add_widget('
  • Hello, now delete me x
  • ',2 ,1); }); $(document).on('click', '#remove'+newid, function() { var gridster = $(".gridster ul").gridster().data('gridster'); gridster.remove_widget( '#block'+newid ); }); });

    对于添加小部件,它工作正常,但我无法删除小部件。

    实际上,您不需要ID来移除小部件。 请检查我的脚本。

      var gridster = $('.gridster ul').gridster().data('gridster'); $(document).on( "click", ".gridster ul li", function() { $(this).addClass("activ"); gridster.remove_widget($('.activ')); }); 

    实际上,您只需要在jQuery元素中包装'#block'+newid ,如函数注释中所述:

     gridster.remove_widget( $( '#block'+newid ) ); 

    函数注释(在jquery.gridster.js中):

     /** * Remove a widget from the grid. * * @method remove_widget 

    * @param {HTMLElement} el jQuery包装要删除的HTMLElement。

      * @param {Boolean|Function} silent If true, widgets below the removed one * will not move up. If a Function is passed it will be used as callback. * @param {Function} callback Function executed when the widget is removed. * @return {Class} Returns the instance of the Gridster Class. */ fn.remove_widget = function(el, silent, callback) {...} 
    • 单击添加后应增加newid var
    • li标签没有正确的id

    请检查下面的代码,应该与您合作

     $(document).ready(function(){ var count = 0; var newid = count + 1; $(document).on("click", "#newGrid", function() { var gridster = $(".gridster ul").gridster().data('gridster'); gridster.add_widget('
  • Hello, now delete me x
  • ',2 ,1); newid++; }); $(document).on('click', '.remove', function() { var gridster = $(".gridster ul").gridster().data('gridster'); gridster.remove_widget( $(this).parent()); }); });

    由于它适用于jQuery对象,因此您无需添加任何类或ID来标识要删除的项目。 只需创建一个click事件并引用$(this)。

     $('body').on( "click", ".gridster ul > li", function() { gridster.remove_widget($(this)); }); 

    或者更有用的东西,你在里面有一个“删除按钮”:

     $('body').on( "click", ".gridster ul > li .remove", function() { gridster.remove_widget($(this).closest('li')); }); 

    这对我有用,我使用时间戳作为唯一ID

    添加项目:

     $( "#addMod").click(function(e) { gridster1.add_widget( '
  • DESCRIPTION
  • ', 1, 1 ); });

    删除项目:

     $('#cashRegisterScreen').on('click', '#delItem', function() { var id=$(this).parent().attr("id"); gridster.remove_widget($(".gridster ul").find("[id='" + id + "']")); });