是否可以将此jquery代码编写得更短? (初学者)

这是我第一次在stackoverflow上问一些东西,请原谅我,如果我做错了什么。 我也是jquery的新手,但通过阅读和教程,我设法创建了一个工作示例。

下面的代码是我创建的。 这意味着我有三个具有可拖动要求的列表和三个可以删除要求的占位符。 我们的想法是,占位符1仅接受列表1中的项目,仅占用列表2中的占位符2和列表3中的占位符3.当拖动需求时,占位符将突出显示,以便用户知道可以将其删除的位置。

现在问题是:有没有办法裁剪这段代码? 我觉得这不是最好的方式,它是三次相同的代码只有两个字正在改变。 正如我从教程中学到的:永远不要写两次。

还有一个问题:是否有可能在占位符中删除需求以在它之间创建一条线? 我希望用户单击一个占位符并单击另一个占位符以绘制连接。 我已经看过很多关于html5 canvas和jsPlumb的例子,但我不需要所有这些function。 单击时占位符之间只有一行。

$(function() { $( "#requirements" ).accordion(); $( "#requirements ul li" ).draggable({ appendTo: "body", helper: "clone" }); $( ".row1 .placeholder" ).droppable({ //makes row1 .placeholder a droppable area accept: "#requirements .row1 li ", activeClass: "ui-state-hover", drop: function( event, ui ) { var $this = $(this); $( "
  • " ).text( ui.draggable.text() ).appendTo( this ); $this.droppable('disable').addClass("highlighted"); } }); $( ".row2 .placeholder" ).droppable({ //makes row2 .placeholder a droppable area accept: "#requirements .row2 li ", activeClass: "ui-state-hover", drop: function( event, ui ) { var $this = $(this); $this.find( ".placeholder" ).remove(); $( "
  • " ).text( ui.draggable.text() ).appendTo( this ); $this.droppable('disable').addClass("highlighted"); } }); $( ".row3 .placeholder" ).droppable({ //makes row3 .placeholder a droppable area accept: "#requirements .row3 li ", activeClass: "ui-state-hover", drop: function( event, ui ) { var $this = $(this); $this.find( ".placeholder" ).remove(); $( "
  • " ).text( ui.draggable.text() ).appendTo( this ); $this.droppable('disable').addClass("highlighted"); } });

    如上所述我是jquery的新手,所以很受欢迎。 提前致谢!

    编写一个返回您正在重用的对象的函数,插入行类或需要在其中更改的任何参数:

     function getSettings(rowClass){ var obj ={ //makes row1 .placeholder a droppable area accept: "#requirements "+rowClass+" li ", activeClass: "ui-state-hover", drop: function( event, ui ) { var $this = $(this); $( "
  • " ).text( ui.draggable.text() ).appendTo( this ); $this.droppable('disable').addClass("highlighted"); } } return obj; }

    然后在$( ".row2 .placeholder" ).droppable(getSettings(".row2")调用它。没有测试它,但是它应该工作。将任何非静态的部分更改为函数参数应该足够了如果用例是您描述的用例。

    欢迎来到jQuery!

    这样的事情应该有效

     var rowArr = [".row1", ".row2", ".row3"]; $(rowArr).each(function(curr) { $(curr + " .placeholder").droppable({ accept: "#requirements " + curr + " li", /*rest of the code remains the same*/ }); }); 

    如何使用这样:

      $( ".row1 .placeholder, .row2 .placeholder, .row3 .placeholder" ).droppable({ //makes row1 .placeholder a droppable area var rowClass = [".row1",".row2", ".row3"]; $(rowClass).each(function(thisrow){ accept: "#requirements" + thisrow + "li ", activeClass: "ui-state-hover", drop: function( event, ui ) { var $this = $(this); $( "
  • " ).text( ui.draggable.text() ).appendTo( this ); $this.droppable('disable').addClass("highlighted"); } }); });