繁体   English   中英

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

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

我想在link_to方法中添加onclick选项以加载模式对话框...我使用的是Rails版本2.3.8,我在google上搜索,无法做到这一点。 请有人帮我吗?

我的link_to方法如下。

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

如果您使用的是2.3.8,则没有:remote => true。 如果尝试执行ajax操作,则需要使用link_to_remote。

因此,它看起来像:

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

和您的新方法将不得不处理类似的ajax请求

country_controller.rb

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

更新

如果除了ajax操作还需要onclick,则可以将其传递到html选项中:

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

您可以将其添加到链接中:

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

然后,您的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