简体   繁体   English

jQuery Sortable仅在第二次单击后触发

[英]Jquery Sortable only fires after second click

I've integrated the jquery "sortable" feature into my website, and it works perfectly with one minor exception. 我已经将jquery的“可排序”功能集成到我的网站中,并且除了一个较小的异常外,它的运行情况非常好。 It only works after I click once anywhere on the page. 只有在页面上的任意位置单击一次后,它才起作用。 The section of the page the sortable elements are found is loaded after an ajax query, so I'm using the "on" function. 页面的可排序元素所在的部分是在ajax查询之后加载的,因此我使用的是“ on”功能。 I'd love to figure out how to get this to work without having to click first. 我很想弄清楚如何使它生效而无需先单击。

 $(document).on("mousedown.sortable", "#container", function() { $("#container").sortable({ update: function(event, ui) { var data = $(this).sortable("serialize"); $.ajax({ data: data, type: 'POST', url: 'myurl' }); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"> </script> <div id="mainContainer"> <ul id="container"> <li id="item-1">Item 1</li> <li id="item-2">Item 2</li> </ul> </div> 

For anyone reading this later, the key to the accepted answer is to have the portion of JQuery code loaded every time the portion of HTML is loaded into the document via AJAX, rather than in a "main" piece of code that's loaded the first time the page itself is loaded. 对于以后阅读本文的人来说,接受答案的关键是每次通过AJAX将HTML的一部分加载到文档中时都加载JQuery代码的部分,而不是在第一次加载的“主”代码段中加载该部分页面本身已加载。

You don't need the mousedown event handler (removed here), since this is causing the sortable to only be added after you do your initial click (as described by yourself) 您不需要mousedown事件处理程序(在此处已删除),因为这导致仅在您初次点击添加可排序项(如您自己所述)

 $("#container").sortable({ update: function(event, ui) { var data = $(this).sortable("serialize"); $.ajax({ data: data, type: 'POST', url: 'myurl' }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"> </script> <div> <ul id="container"> <li id="item-1">Item 1</li> <li id="item-2">Item 2</li> </ul> </div> 

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

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