简体   繁体   English

在Rails的link_to方法中添加onclick选项?

[英]Adding an onclick option to link_to method in rails?

I want to add an onclick option to link_to method for loading an modal dialog box...i am using rails version 2.3.8 and i searched on google and could not do it. 我想在link_to方法中添加onclick选项以加载模式对话框...我使用的是Rails版本2.3.8,我在google上搜索,无法做到这一点。 Plz anybody help me? 请有人帮我吗?

My link_to method as follows. 我的link_to方法如下。

<%= link_to 'All countries',{:controller=>'countries', :action=>'new'}, :remote => true %>

If you are using 2.3.8, you don't have :remote => true. 如果您使用的是2.3.8,则没有:remote => true。 You need to use link_to_remote if you are try to do an ajax action. 如果尝试执行ajax操作,则需要使用link_to_remote。

So it would look something like: 因此,它看起来像:

<%= link_to_remote 'All countries', :url => {:controller => 'countries', :action => 'new'}%>
<div id="populate_me"></div>

and your new method would have to handle the ajax request with something like 和您的新方法将不得不处理类似的ajax请求

countries_controller.rb country_controller.rb

def new
  <do something>
  render :update do |page|
    page.replace_html 'populate_me', :partial => 'whatever'
  end
end

UPDATED 更新

If you want the onclick in addition to the ajax action, you can just pass it into the html options: 如果除了ajax操作还需要onclick,则可以将其传递到html选项中:

<%= link_to_remote 'All countries', :url => {:controller => 'countries', :action => 'new'}, :html => {:onclick => 'alert("some javascript executed before ajax")'} %>

You can add this to the link: 您可以将其添加到链接中:

, :class => "pop light", :id => "modal_link"

Then, your JS shows something ilke this: 然后,您的JS会显示以下内容:

<script type="text/javascript">
    $(document).ready(function() {
      $('a.poplight[href^=#]').click(function() {
        var popID = $(this).attr('rel'); //Get Popup Name
        var popURL = $(this).attr('href'); //Get Popup href to define size
        var query= popURL.split('?');
        var dim= query[1].split('&');
        var popWidth = dim[0].split('=')[1]; //Gets the first query string value
        $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"></a>');
        $('a.close').hide();
        var popMargTop = ($('#' + popID).height() + 80) / 2;
        var popMargLeft = ($('#' + popID).width() + 80) / 2;
        $('#' + popID).css({
            'margin-top' : -popMargTop,
            'margin-left' : -popMargLeft
        });
        $('body').append('<div id="fade"></div>');
        $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
        return false;
      });
      $('a.close').live('click', function() {
          $('#fade , .popup_block').fadeOut(function() {
            $('#fade, a.close').remove(); 
          });
          return false;
      });         
      $('#modal_link').click();
    });
  </script>

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

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