简体   繁体   English

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

[英]remove .each from jquery selector in coffeescript

I have coffee script below, to do remote ajax select2, this will set all class select2-autocomplete, the problem is I would like to put this script to just one item that just added, how I modify this script below without iterating each, 我在下面有coffee脚本,可以执行远程ajax select2,这将设置所有类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 

below is my HTML code, note: since I'm using select2 v.3.5.3 ajax I'm using hidden field (rails) 以下是我的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? }" %>

Create a small jQuery plugin that gets executed on element when called. 创建一个小的jQuery插件,该插件在调用时将在element上执行。

$.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

And call this on element on which you want it to be enabled. 并在要启用它的元素上调用它。 Like below 像下面

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM