从 coffeescript 中的 jquery 选择器中删除 .each

remove .each from jquery selector in coffeescript

我下面有咖啡脚本,要执行远程 ajax select2,这将设置所有 class select2-autocomplete,问题是我想把这个脚本只放在一个项目上添加,我如何在下面修改这个脚本而不迭代每个脚本,

    $('.select2-autocomplete').each (i, e) ->
    select = $(e)
    options = 
      multiple: false
      width: "98%"
      placeholder: "Type Hotel name"
      minimumInputLength: 3
    options.ajax =
      url: select.data('source')
      dataType: 'json'
      type: "GET"
      quietMillis: 150
      # input untuk program
      data: (term) ->
        q: term
      results: (data) ->
        results: $.map(data, (item) ->
          text: item.name
          id: item.id
        )
    options.dropdownCssClass = 'bigdrop'
    select.select2 options 

下面是我的 HTML 代码,注意:因为我使用的是 select2 v.3.5.3 ajax 我使用的是隐藏字段 (rails)

        <%= f.hidden_field :hotel_id, data: { source: search_name_hotels_path }, class: "select2-autocomplete", :value => "#{f.object.hotel_id unless f.object.new_record? || f.object.hotel_id.nil? }" %>

创建一个小的 jQuery 插件,调用时在元素上执行。

$.fn.enableAutocomplete = () ->
    select = this
    options = 
      multiple: false
      width: "98%"
      placeholder: "Type Hotel name"
      minimumInputLength: 3
    options.ajax =
      url: select.data('source')
      dataType: 'json'
      type: "GET"
      quietMillis: 150
      # input untuk program
      data: (term) ->
        q: term
      results: (data) ->
        results: $.map(data, (item) ->
          text: item.name
          id: item.id
        )
    options.dropdownCssClass = 'bigdrop'
    select.select2 options

然后在您希望启用它的元素上调用它。喜欢下面

$('#selectElement').enableAutocomplete();