【发布时间】:2014-09-10 17:44:54
【问题描述】:
我有一个使用 cocoon 的 rails 应用程序
= link_to_add_association
调用部分表单
在主窗体上,我有咖啡脚本来加载 select2 元素的所有数据
当插入 ajax 部分时,select2 元素不会出现。我需要实例化它。
这是我的表单coffee/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 是我的宿敌,我真的觉得很痛苦.....
帮助!
【问题讨论】:
-
$(inserted_item).find(".select2").select2
标签: ruby-on-rails jquery-select2 cocoon-gem