簡體   English   中英

使用jQuery切換Rails局部

[英]Toggling rails partials using jQuery

我試圖在我的Rails應用程序中使用jQuery,實質上是在單擊按鈕時在兩個部分之間切換。 所需的行為如下:頁面呈現有用戶的個人資料和“編輯個人資料”按鈕。 單擊概要文件部分上的“編輯概要文件”按鈕時,將從DOM中刪除該部分,並呈現編輯概要文件部分。 單擊編輯概要文件部分上的“保存”按鈕時,操作應撤消並再次顯示用戶的概要文件。 我是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>

我的html.erb如下:

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

我的問題是,我似乎只能運行一個功能(即頁面加載,並且可以切換以進行編輯,但不能返回)。 任何指導將不勝感激。

根據您應該使用的jQuery版本

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

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

#edit相同。

jQuery中的bind和live方法有什么區別?

簡而言之:.bind()僅適用於您當前在jQuery對象中選擇的項目。 .live()將應用於所有當前匹配的元素,以及將來可能添加的任何元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM