Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

jquery - Rails - ajax select menu only firing once?

I know this question gets asked a lot, but none of the solutions have helped. I have a select menu that works the first time no problem, but won't execute again until the page has reloaded.

<div class="dynamic">
<%= render 'status_selector' %>
</div>

This is what is inside the partial:

<%= form_for @report, :remote => true, :html => {:id => 'report-edit-status'} do |f| %>
    <%= f.hidden_field :report_id, :value => @report.id  %>
    <%= f.select(:status, STATUS, {},:class => "status-change-selector", :style => "font-size:1.1em;") %>
<% end %>

And here is the Application.js:

$('.status-change-selector').unbind('change');
$('.status-change-selector').change(function(event) {
    event.preventDefault();
    $(this).closest('form').submit();
});

Update.js.erb

$('.dynamic').html("<%= escape_javascript(render(:partial => 'reports/status_selector')).html_safe %>");

EDIT:

Based on Peter Goldstein's suggestion, I added a listener to a Parent element, so I don't need to add the Jquery code to my Update.js.erb. This is what I have in my Application.js now:

$('.dynamic').on('change', '.status-change-selector', function(event) {
    event.preventDefault();
    $(this).closest('form').submit();
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So your update is creating a new element to which your change event does not apply. The JS change binds to elements that exist at the time of execution. One easy way to fix the issue is to add:

$('.status-change-selector').unbind('change');
$('.status-change-selector').change(function(event) {
  event.preventDefault();
  $(this).closest('form').submit();
});

to the end of your Update.js.erb. That will bind the newly created DOM element. Other solutions which are more DRY are a little more complex, but basically involve attaching a listener to a parent element of the DOM you're inserting rather than to the element itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...