简体   繁体   中英

Toggling rails partials using jQuery

I'm trying to use jQuery in my rails application to essentially toggle between two partials on the click of a button. The desired behavior is as follows: the page renders with the user's profile and an 'edit profile' button. When the 'edit profile' button on the profile partial is clicked the partial is removed from the DOM and the edit profile partial is rendered. When the 'save' button on the edit profile partial is clicked the action should reverse and show the user's profile again. I'm new to jQuery, but with the help of stackoverflow I arrived at the following script:

<script language="javascript" type="text/javascript">
  jQuery(
    function editProfile($) {
      $('#edit').click(function() {
        $("#edit-profile").html('<%= escape_javascript(render :partial => "shared/edit_profile").html_safe %>');
        $("#show-profile").empty();
      });
    }
  );

  jQuery(
    function showProfile($) {
      $('#save').click(function() {
        $("#show-profile").html('<%= escape_javascript(render :partial => "shared/show_profile").html_safe %>');
        $("#edit-profile").empty();
      });
    }
  );
</script>

My html.erb is as follows:

<div id="show-profile">
  <%= render :partial => "shared/show_profile" %>
</div>
<div id="edit-profile"></div>

The problem I have is that I can only seem to run one function (ie page loads and I can toggle to edit, but not back). Any guidance would be appreciated.

Depending on the version of jQuery you should use

Prior to 1.7: $('#save').live('click', function(){...})

1.7 and higher: $('#save').on('click', function(){...})

And the same for #edit .

What is the difference between the bind and live methods in jQuery?

In short: .bind() will only apply to the items you currently have selected in your jQuery object. .live() will apply to all current matching elements, as well as any you might add in the future.

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