简体   繁体   中英

Jquery/Ajax Done Event Only Running Once

The following code successfully runs and adds new values to the database...

<script type="text/javascript">
$(document).ready(function() {
  var i = 0;
  $(".testClick").click(function () {
    var dbvalue = $(this).data('dbvalue');
    var task_id = $(this).data('wrkval');
    $.ajax({
      type: 'POST',
      url: '/tasks/update_sub_task',
      dataType: 'json',
      data: {
        tasks: {
          id: task_id,
          subtask_id: dbvalue
        }
      },
    }).done(function() {
      console.log("SUCCESS");
      $("#working_area").html("<%= escape_javascript(render(:partial => 'sub_tasks.js.erb', locals: {items: params[:w]} )) %>");
    });
  });
});
</script>

<% @days.each do |e| %>
    <a id="ID=1" class="testClick" data-dbvalue="<%= e.id %>"  data-wrkval="<%= params[:w] %>"><%= e.name %></a>
<% end %>

It logs "SUCCESS" in the console and replaces the current content of the #working_area div with the partial.

Fantastic...

However when I click the next link, it logs another SUCCESS message but for some reason it doesn't replace the #working_area content again.

Does anyone have any ideas how I can get this to replace/refresh each time a link is clicked?

Update - Okay I've got it reloading and I've realised that it because my partial was rendered when the modal was clicked it was fixed "as-of that time".

You should use on instead like this:

$(document).on("click",".testClick",function (){
    ..code here...
});    

Use an 'on' event.

Replace

$(".testClick").click(function () {

with

$(".testClick").off('click').on('click', function() {

Also make sure that #working_area is still valid after replacing the content for the first time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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