我使用Select2帮助在列表中选择多个选项。问题是,当我想对表单的一部分使用相同的函数时,我重复了相同的代码。
我想知道一种干扰代码的方法。非常感谢。
$(document).ready ->
$(".universities-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.dropdownCssClass = "bigdrop"
options.multiple = true
options.width = "200px"
options.initSelection = (element, callback) ->
id = undefined
id = $(element).val()
if id isnt null
$.ajax(
url: '/universities/multiple'
dataType: "json"
data:
id: id
).done (data) ->
results = undefined
results = []
callback data
return
select.select2 options
return
return
$(document).ready ->
$(".skills-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: datea
options.dropdownCssClass = "bigdrop"
options.multiple = true
options.width = "200px"
options.initSelection = (element, callback) ->
id = undefined
id = $(element).val()
if id isnt null
$.ajax(
url: '/skills/multiple'
dataType: "json"
data:
id: id
).done (data) ->
results = undefined
results = []
callback data
return
select.select2 options
return
return
答案 0 :(得分:1)
您可以将类名称设为变量并命名您的函数
所以:
setupSelect = (target) ->
$(target).each (i, e) ->
select = $(e)
#etc
$ ->
setupSelect('.universities-select2')
setupSelect('.skills-select2')
当然你也可以用jquery选择器选择多个类,所以如果它只是这两个你可以这样做
$('.universities-select2, .skills-select2')