0

我有一个表单元素,它根据 ajax 的请求被拉入。然后,我尝试对插入的文本框执行 ajax 请求,以在键入时查找位置。该代码适用于第一个文本框,但在插入第二个文本框时会失败。我试图让脚本在 ajax 完成后重新加载,但它仍然无法工作。帮助将不胜感激。

Form.html.erb - 设置 rails 嵌套表单并拉入部分

  <%= nested_form_for(@post, :html=> {:multipart => true, :class=> "new_blog_post", :id=> "new_blog_post"}) do |f| %>

  ...

  <fieldset>
   <%= render :partial => 'search_locations', :locals => { :f => f }  %>

  </fieldset>

  <p><%= f.link_to_add "Add a location", :locations %></p>

  ...

  <% end %>

partial.html.erb - 在页面加载时拉入,然后在按下“添加位置”按钮时拉入

  <fieldset>
  <%= f.fields_for :locations do |m| %>    
        <%= m.text_field :name ,:class=>"localename", :placeholder=> "Name of the location", :autocomplete => "off" %>
        <%= m.text_field :longitude, :class => "long" %>
        <%= m.text_field :latitude, :class => "lat" %>
        <div class="latlong">
        <p class="help-block">Enter the name of the town or city visited in this blog entry.</p>
        </div>
        <%= m.link_to_remove "Remove this location" %>

   <% end %>
  </fieldset>

Javascript(位于表单底部)

<script type="text/javascript">


    function locationchecker() {

    // Rails to multiply the script 20 times            
    <% (0..20).each do |i| %>

    // when the #search field changes
    $(".localename:eq(<%=i%>)").keyup(function() {

    // get the value of searchfield 
        var location<%=i%> = $(".localename:eq(<%=i%>)").val(); 

    //Take the value of the textbox and pull it from geocoder
    $.get('/locations/location?location='+location<%=i%>,this.value, function(searchone<%=i%>) {
    $(".latlong:eq(<%=i%>)").html(searchone<%=i%>);

     })
        // Upon complete run the script again
    .complete(function(searchone<%=i%>) { locationchecker });


    });

    <%end%>
}
       // load script on doc ready
$(document).ready(locationchecker);


</script>

帮助会很棒!

提前致谢,

詹姆士

4

1 回答 1

1

您应该使用.on()jQuery api doc)方法来附加您的 keyup 事件处理程序,如下所示:

$('#myForm').on('keyup','.localename',function() {
       // stuff here
       var location = $(this).val(); // this = element on which the event was triggered
});
于 2012-10-18T18:01:41.713 回答