简体   繁体   English

将动态创建的列表项 ID 绑定到 jQuery 插件

[英]Bind Dynamically Created List Item Id To jQuery Plugin

I am trying to create a drag and drop feature that I already implemented using a jQuery plugin.我正在尝试创建一个已使用jQuery插件实现的拖放功能。 Here is what I used:这是我使用的:

 $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection();
 #sortable1, #sortable2 { border: 1px solid #eee; width: 142px; min-height: 20px; list-style-type: none; margin: 0; padding: 5px 0 0 0; float: left; margin-right: 10px; } #sortable1 li, #sortable2 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; }
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <ul id="sortable1" class="connectedSortable"> <li class="ui-state-default">Item 1</li> <li class="ui-state-default">Item 2</li> <li class="ui-state-default">Item 3</li> <li class="ui-state-default">Item 4</li> <li class="ui-state-default">Item 5</li> </ul> <ul id="sortable2" class="connectedSortable"> <li class="ui-state-highlight">Item 1</li> <li class="ui-state-highlight">Item 2</li> <li class="ui-state-highlight">Item 3</li> <li class="ui-state-highlight">Item 4</li> <li class="ui-state-highlight">Item 5</li> </ul>

This works perfect and the plugin uses few built-in events to manipulate those list items.这很完美,插件使用很少的内置事件来操作这些列表项。 Now the problem is, I am stuck with those events when I try to bind the list items from Ajax call.现在的问题是,当我尝试绑定来自Ajax调用的列表项时,我遇到了这些事件。 Something like this:像这样的东西:

var html = "";
html += '<ul id="sortable1" class="connectedSortable">';
$.each(value.DataFromDb, function (key, val) {
   html += '<li class="ui-state-default">' + val + '</li>';
})
html += '</ul>';

$( "#sortable1, #sortable2" ).sortable({
   connectWith: ".connectedSortable"
}).disableSelection();

So the drag and drop feature actually doesn't work when created the list items dynamically from database or Ajax call.因此,当从数据库或Ajax调用动态创建列表项时,拖放功能实际上不起作用。 Any way that I can make it with Ajax call?有什么方法可以通过Ajax调用来实现吗?

It means you have binded the drag and drop event prior to element actually gets created in the DOM.这意味着您在元素实际在 DOM 中创建之前绑定了拖放事件。 In that case you can follow two approaches, you can follow any of those.在这种情况下,您可以遵循两种方法,您可以遵循其中任何一种方法。

  1. After creating li elements through ajax call, add teh drag and drop event handler to it.通过 ajax 调用创建 li 元素后,向其添加拖放事件处理程序。
  2. (Event bubbling) add the event handler to the parent element of the li s then using event.target find whether teh event created by li or not start drag and drop. (事件冒泡)将事件处理程序添加到li的父元素然后使用 event.target 查找li创建的事件是否开始拖放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM