0

我在一个页面上有 2 个不同的自动完成字段,每个字段都从数据库中的不同来源填充。我的问题是当我测试页面时,两个自动完成行为有时会在彼此的文本字段中切换。

我的视图部分如下所示(我遵循了railscasts):

<fieldset>
  <%= f.text_field :ability_title, {:class => 'autocomplete_field', data: { autocomplete_source: abilities_path } } %>
  <%= f.label :points %>: <%= f.text_field :points %>
  <%= f.hidden_field :_destroy %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

<fieldset>
  <%= f.text_field :mission_title, {:class => 'autocomplete_field', data: {autocomplete_source: missions_path } } %>
  <%= f.hidden_field :_destroy %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

我的JavaScript:

jQuery ->
  $('fieldset').live 'click', ->
    $('.autocomplete_field').autocomplete
      source: $('.autocomplete_field').data('autocomplete-source')

我的控制器:

def index
  if params[:term].present?
    @abilities = Ability.search_titles(params[:term])
  else
    @abilities = Ability.all
  end

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @abilities }
  end
end

def index
  if params[:term].present?
    @missions = Mission.search_titles(params[:term])
  else
    @missions = Mission.all
  end

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @missions.map(&:title) }
  end
end

谢谢

4

2 回答 2

2

我认为您只需要按 id 区分两个文本字段,例如:

<fieldset>
  <%= f.text_field :ability_title, {:id => 'autocomplete_field1', data: { autocomplete_source: abilities_path } } %>
  <%= f.label :points %>: <%= f.text_field :points %>
  <%= f.hidden_field :_destroy %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

<fieldset>
  <%= f.text_field :mission_title, {:id => 'autocomplete_field2', data: {autocomplete_source: missions_path } } %>
  <%= f.hidden_field :_destroy %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>
My javascript:

jQuery ->
  $('fieldset').live 'click', ->

    $('#autocomplete_field1').autocomplete
      source: $('#autocomplete_field1').data('autocomplete-source')
    $('#autocomplete_field2').autocomplete
      source: $('#autocomplete_field2').data('autocomplete-source')

编辑:更优雅的解决方案:

jQuery ->
  $('fieldset').live 'click', ->
    $('#autocomplete_field1, #autocomplete_field2').each (index, element) =>
      $(element).autocomplete
        source: $(element).data('autocomplete-source')
于 2012-10-08T09:57:32.197 回答
0

试试这是否可行,请替换您的 js 文件中的源代码

source: $(this).data('autocomplete-source') 
于 2012-10-08T10:14:16.213 回答