简体   繁体   English

使用jQuery切换Rails局部

[英]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. 我试图在我的Rails应用程序中使用jQuery,实质上是在单击按钮时在两个部分之间切换。 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. 单击概要文件部分上的“编辑概要文件”按钮时,将从DOM中删除该部分,并呈现编辑概要文件部分。 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: 我是jQuery的新手,但是在stackoverflow的帮助下,我到达了以下脚本:

<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: 我的html.erb如下:

<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 根据您应该使用的jQuery版本

Prior to 1.7: $('#save').live('click', function(){...}) 1.7之前的版本: $('#save').live('click', function(){...})

1.7 and higher: $('#save').on('click', function(){...}) 1.7及更高版本: $('#save').on('click', function(){...})

And the same for #edit . #edit相同。

What is the difference between the bind and live methods in jQuery? jQuery中的bind和live方法有什么区别?

In short: .bind() will only apply to the items you currently have selected in your jQuery object. 简而言之:.bind()仅适用于您当前在jQuery对象中选择的项目。 .live() will apply to all current matching elements, as well as any you might add in the future. .live()将应用于所有当前匹配的元素,以及将来可能添加的任何元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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