jQuery可在动态创建的div上排序 [英] Jquery sortable on dynamically created divs
问题描述
我有一个Rails 4应用程序,该应用程序具有嵌套字段,并且我正在尝试使jQuery可排序用于产品.
I have a rails 4 app that has nested fields and I'm trying to get jQuery sortable working on products.
这是我的代码:
<div class="form-group" id='products'>
<%= f.fields_for :products do |builder| %>
<%= render 'product_fields', f: builder %>
<% end %>
</div>
和我的product_fields部分看起来像:
and my product_fields partial looks like:
<div class='product'>
test
</div>
我的jQuery如下:
and my jQuery looks like:
$('#products').sortable({
items: ".product"
});
$('form').on('click', '.add_fields', function(e) {
var regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$(this).before($(this).data('fields').replace(regexp, time));
return e.preventDefault();
});
基本上,正在发生的事情是,在加载时(通过Rails),我在页面上已经有一个.product
.然后,当您单击按钮时,我会有一些jQuery生成相同的.product
div.但是只有第一个.product
(由Rails服务器端创建的那个)是唯一可排序的.
Basically, what's happening is that I already have one .product
on the page, when it is loaded (via Rails). Then when you click a button I have some jQuery that generates identical .product
divs. But only the first .product
(the one that is created by Rails server-side) is the only one that is sortable.
推荐答案
初始化可排序对象,以便它选择新添加的对象.无论如何这都是有意义的,因为您无需进行排序最初的单个.product
initialize sortable each time you add a new .product so that it picks up the new addition.. which makes sense anyway, as you won't need to sort the initial single .product
之后...
$(this).before($(this).data('fields').replace(regexp, time));
放入..
$('#products').sortable({
items: ".product"
});
或..
$('#products').sortable('refresh');
这篇关于jQuery可在动态创建的div上排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!