Jquery 模态窗口和编辑对象 [英] Jquery modal windows and edit object

查看:24
本文介绍了Jquery 模态窗口和编辑对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一些模式窗口,以便在用户想要编辑对象时显示.我以前没有这样做过,我已经寻找了教程,但没有得到一些直接的答案,我得到的只是更加困惑!可以使用的库似乎太多了.

所以我想这个问题分为两部分.如果我想这样做,有什么特别的原因让我想选择 Jquery 而不是原型吗?还有更多选择吗?

第二部分实际上是在做,在这一点上我真的不在乎使用哪个库.

我有以下标准 crud、编辑和更新操作.现在,我想要的是当用户单击编辑时,而不是转到页面,弹出一个窗口,他可以在其中编辑票证的名称(这是目前唯一的属性).

在控制器中我有这个:

def 编辑@ticket = Ticket.find(params[:id])结尾定义更新@ticket = Ticket.find(params[:id])如果@ticket.update_attributes(params[:ticket])redirect_to ticket_url, :notice =>已成功更新票证."别的渲染:动作=>'编辑'结尾结尾

谁能帮我解决这个问题?当然也非常欢迎建议和链接!

解决方案

更新:这是使用 CoffeeScript 对此答案的 Rails 5 改编:https://gist.github.com/1456815

<小时>

jQuery 更受欢迎是有充分理由的,我不会深入探讨.其他地方有很多.

假设您想使用 jQuery,设置非常简单:

# 将以下内容添加到`group :development` 下的 Gemfile 中宝石'jquery-rails'# 运行以下命令$捆绑# 然后让生成器安装$ rails g jquery:install

然后更新您的 Application.rb javascript 扩展默认值:

# 你想要的 JavaScript 文件:defaults(application.js 总是包含在内).config.action_view.javascript_expansions[:defaults] = %w(jquery rails)

并确保您的布局文件(例如 application.html.erb)包含这些文件:

<%= javascript_include_tag :defaults %>

<小时>

对于你的模态,有很多关于如何去做的意见.我个人更喜欢根据应用程序的需要滚动我自己的模态窗口.只需要几行带有 jQ​​uery 的 JS 就可以构建与 Rails.js 配合得很好的模态:

# 在一个视图中,可能是包含在一个 _modal.html.erb 部分# 您的布局(可能在底部).<div id="modal-container"></div><div id="modal"><a href="#" class="close">close</a>

以下是我使用的模态的一些样式(scss 样式):

#modal-container {显示:无;位置:固定;顶部:0;右:0;底部:0;左:0;背景:RGBA(0,0,0,0.4);}#modal {显示:无;位置:绝对;宽度:600px;左:50%;margin-left: (-600px - 40px)/2;填充:20px;背景:#fff;边框:5px 实心 #eee;&>.关闭 {位置:绝对;右:5px;顶部:5px;颜色:#666;&:hover, &:active {颜色:#000;}}}

这让样式/视图不受影响.您可能希望自定义这些样式以更好地适应您的应用程序,但它们非常通用,因此应该可以开始使用.

要将其集成到 Rails 中,有两个部分.首先,您需要让浏览器发送对内容的 AJAX 请求并在返回时显示模态.其次,您需要 Rails 做出适当的响应.

发送 AJAX 和处理响应需要使用 :remote =>;true 在要远程发送的链接/表单上.

<%= link_to 'New Post', new_post_path, :remote =>真%>

这将在 Rails.js 将选择的链接上创建一个数据属性,允许它自动远程提交.它期望一个 javascript 返回,当它得到它时它会执行那个响应.您可以为每个操作 respond_to 块添加一个快速的 format.js,并创建一个包含所需 JS 的随附 new.js.erb 文件实际填写并显示模态.没关系,但是我们可以通过返回没有布局的模板并将模态显示/隐藏职责移到 application.js 中来稍微干点它:

# 在您的应用程序控制器中,您需要将 XHR (ajax) 请求的布局设置为 nil类 ApplicationController <动作控制器::基础布局 Proc.new { |控制器|控制器.request.xhr??零:'申请' }结尾

使整个事情工作的 javascript:

# in application.js$(函数(){var $modal = $('#modal'),$modal_close = $modal.find('.close'),$modal_container = $('#modal-container');# 这一点可能会令人困惑.由于 Rails.js 发送了一个接受标头,要求# javascript,但我们希望它返回 HTML,我们需要重写它.$('a[data-remote]').live('ajax:beforeSend', function(e, xhr, settings){xhr.setRequestHeader('accept', '*/*;q=0.5, text/html, ' + settings.accepts.html);});# 使用 data-remote 属性处理模态链接$('a[data-remote]').live('ajax:success', function(xhr, data, status){$modal.html(数据).prepend($modal_close).css('top', $(window).scrollTop() + 40).展示();$modal_container.show();});# 隐藏关闭按钮点击$('.close', '#modal').live('click', function(){$modal_container.hide();$modal.hide();返回假;});});

我有一些逻辑可以将模态窗口定位在距浏览器当前滚动位置 40 像素的位置.

有了所有这些部分,当你点击一个带有远程属性集的链接/表单时,Rails.js 将处理提交请求,你的应用程序将知道只返回没有布局的操作模板,非常适合在模态窗口中显示它,然后我们上面的 javascript 将挂接到 Rails.js 的 ajax:success 回调中,并使用从我们的应用程序返回的模板 HTML 显示模态.

<小时>

给猫剥皮的方法不止一种,构建此功能的方法也有十几种.这绝对是 Rails 团队尚未制定更强大约定的领域.这只是我的处理方式,我觉得它相当 DRY,需要最少的努力,并且相当灵活且面向未来.也许有人可以在此基础上构建的领域之一是使用涵盖更多基础且功能更丰富的模态/灯箱框架.如果有人这样做,我很乐意看到写一篇文章!

I am trying to create some modal windows to appear whenever the user wants to edit the object. I haven't done this before, and I've looked for tutorials, but instead of getting some straight forward answers, all I got is more confused! There seem to be sooo many libraries one can use.

So I guess this question is in two parts. If I wanted to do this, are there any particular reasons why I would want to choose Jquery over prototype? Are there more options?

Second part is actually doing it, at this point i don't really care using which library.

I have the following, standard crud, edit and update actions. Now, what I would like is when the user clicks edit, instead of going to the page, pop up a window where he can edit the name of the ticket (this is the only attribute for now).

in the controller I have this:

def edit
  @ticket = Ticket.find(params[:id])
end

def update
  @ticket = Ticket.find(params[:id])
  if @ticket.update_attributes(params[:ticket])
    redirect_to tickets_url, :notice  => "Successfully updated ticket."
  else
    render :action => 'edit'
  end
end

Can anyone please help me with this? Also of course advice and links are more than welcome!

解决方案

UPDATE: Here is a Rails 5 Adaptation of this answer using CoffeeScript: https://gist.github.com/1456815


jQuery is more popular for good reasons that I won't go into. Plenty on that elsewhere.

Assuming you want to use jQuery, the setup is pretty straightforward:

# add the following to your Gemfile under `group :development`
gem 'jquery-rails'

# run the following
$ bundle

# then let the generator install
$ rails g jquery:install

And then update your Application.rb javascript expansion defaults:

# JavaScript files you want as :defaults (application.js is always included).
config.action_view.javascript_expansions[:defaults] = %w( jquery rails )

And make sure your layout file (e.g. application.html.erb) is including those files:

<%= javascript_include_tag :defaults %>


For your modal, there are a lot of opinions on how to do it. Personally I prefer to roll my own modal windows based on the needs of the application. It's only a few lines of jQuery-laced JS to build modals that work really well with Rails.js:

# in a view, perhaps a _modal.html.erb partial that is included into 
# your layout (probably at the bottom).
<div id="modal-container"></div>
<div id="modal">
  <a href="#" class="close">close</a>
</div>

Here are some styles (scss style) for the modal that I use:

#modal-container {
  display: none;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0,0,0,0.4);
}

#modal {
  display: none;
  position: absolute;
  width: 600px;
  left: 50%;
  margin-left: (-600px - 40px) / 2;
  padding: 20px;
  background: #fff;
  border: 5px solid #eee;

  & > .close {
    position: absolute;
    right: 5px;
    top: 5px;
    color: #666;
    &:hover, &:active {
      color: #000;
    }
  }
}

That gets the styles/views out of the way. You might want to customize those styles to fit your application better, but they're pretty generic so they should work to start.

To get it integrated into Rails, there are 2 parts. First, you need to get the browser to send AJAX requests for content and show the modal on return. Second, you need Rails to respond with an appropriate response.

Sending AJAX and handling the responses entails using :remote => true on the links/forms you want to be sent remotely.

<%= link_to 'New Post', new_post_path, :remote => true %>

That'll create a data attribute on the link that Rails.js will pickup, allowing it to be submitted remotely automatically. It expects a javascript return, and it'll execute that response when it gets it. You can add a quick format.js to each actions respond_to block, and create an accompanying new.js.erb file that contains the JS needed to actually fill in and show the modal. That's okay, but we can DRY it up a bit more than that by returning the template without a layout and moving the modal showing/hiding responsibilities into application.js:

# in your app controller, you'll want to set the layout to nil for XHR (ajax) requests
class ApplicationController < ActionController::Base
  layout Proc.new { |controller| controller.request.xhr? ? nil : 'application' }
end

The javascript to make the whole thing work:

# in application.js
$(function(){
  var $modal = $('#modal'),
      $modal_close = $modal.find('.close'),
      $modal_container = $('#modal-container');

  # This bit can be confusing. Since Rails.js sends an accept header asking for
  # javascript, but we want it to return HTML, we need to override this instead.
  $('a[data-remote]').live('ajax:beforeSend', function(e, xhr, settings){
    xhr.setRequestHeader('accept', '*/*;q=0.5, text/html, ' + settings.accepts.html);
  });

  # Handle modal links with the data-remote attribute
  $('a[data-remote]').live('ajax:success', function(xhr, data, status){
    $modal
      .html(data)
      .prepend($modal_close)
      .css('top', $(window).scrollTop() + 40)
      .show();
    $modal_container.show();
  });

  # Hide close button click
  $('.close', '#modal').live('click', function(){
    $modal_container.hide();
    $modal.hide();
    return false;
  });
});

I've got some logic in there to position the modal window 40px from the current scroll position of the browser.

With all of these pieces in place, when you click on a link/form with a remote attribute set, Rails.js will handle submitting the request, your application will know to return just the template for the action without the layout, perfect for displaying it in a modal window, and then our javascript above will hook into the ajax:success callback from Rails.js and display the modal with the template HTML returned from our application.


There's more than one way to skin a cat, and more than a dozen ways of building this functionality. This is definitely an area that stronger conventions have yet to be set by the Rails team. This is merely my way of handling this that I feel is fairly DRY, requires minimal effort, and is fairly flexible and future-proof. Perhaps one of the areas that someone could probably build on this is to use a modal/lightbox framework that covers more bases and is more feature-rich. And if someone does that, I'd love to see a write up!

这篇关于Jquery 模态窗口和编辑对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆