我有一个使用 cocoon 的 rails 应用程序
= link_to_add_association
调用部分形式
在主窗体上,我有咖啡脚本来加载 select2 元素的所有数据
插入 ajax 部分时,不会出现 select2 元素。我需要实例化它。
这是我的表格咖啡/js
$(document).ready ->
$(".select2").each (i, e) ->
select = $(e)
options = {}
if select.hasClass("ajax")
options.ajax =
url: select.data("source")
dataType: "json"
data: (term, page) ->
q: term
page: page
per: 10
results: (data, page) ->
results: data
options.placeholder = "Select a value"
options.allowClear= "true"
options.dropdownAutoWidth = "true"
options.initSelection = (element, callback) ->
data = {id: element.val().split('||')[0], text: element.val().split('||')[1]};
callback data
select.select2 options
return
如果我使用 coocon - 绑定后插入
$('body').bind 'cocoon:after-insert', (e, inserted_item) ->
$(".select2").each (i, e) ->
select = $(e)
options = {}
if select.hasClass("ajax")
options.ajax =
url: select.data("source")
dataType: "json"
data: (term, page) ->
q: term
page: page
per: 10
results: (data, page) ->
results: data
options.placeholder = "Select a value"
options.allowClear= "true"
options.dropdownAutoWidth = "true"
options.initSelection = (element, callback) ->
data = {id: element.val().split('||')[0], text: element.val().split('||')[1]};
callback data
select.select2 options
return
我刷新了页面上的所有元素 - 自然地,我调用了所有 select2 对象。我没有为 select2 js 编写此代码。
所有现有的表单元素都可以,但是动态添加的那些元素会被刷新 - 所以它们会失去它们所拥有的值。
我只想选择添加的元素并使其工作。
如果我尝试
$('body').bind 'cocoon:after-insert', (e, inserted_item) ->
$(inserted_item).find(".select2").select2
return
它也不起作用
尝试了很多选择,但我的头发现在很薄,我需要帮助。JS是我的宿敌我真的觉得很痛苦.....
帮助!