使用:remote =>悬停事件为true [英] Using :remote => true with hover event

查看:44
本文介绍了使用:remote =>悬停事件为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Rails中调用Ajax调用.我已经看到了使用:remote 选项的一种好方法.我有这个工作示例:

I want to invoke an Ajax call in Rails. I've seen a good way of doing so with the :remote option. I've got this working example:

<%= button_to('Get Transfers', {:action => 'get_transfers', :section_id => params[:section_id]}, :method => :get, :remote => true) %>

但是,我不希望用户通过按下按钮或单击链接来调用呼叫,而是希望在Javascript事件(将鼠标悬停在元素上)上调用它.

However, I don't want the user to invoke the call by pressing a button or clicking a link, but rather invoke it on a Javascript event (hovering over an element).

是否有一种使用:remote =>的方法?true ,但是将鼠标悬停在某个元素上时会自动调用它吗?如果是,怎么办?

Is there a way to use :remote => true, but invoke it automatically when hovering over an element? If yes, how?

推荐答案

选项1

要使按钮响应单击并将鼠标悬停在其他div上,您可以尝试执行以下操作:

To make the button respond to click and hover over some other div you can try doing the following:

在您的视图中,为按钮提供一个唯一的ID,并向应作为触发器的元素中添加一些类:

In your view you give the button a unique id and add some class to an element that should be act as a trigger:

<%= button_to('Get Transfers', {action: 'get_transfers', section_id: params[:section_id]}, method: :get, remote: true}, {id: 'remote_hover_button'}) %>
<div class="some_trigger">Hover me!</div>

在您的js中,您想绑定到该触发元素并触发按钮上的click事件:

In your js you want to bind to that trigger element and trigger the click event on the button:

$(document).ready(function(){
  $('.some_trigger').hover(function(){
    $('#remote_hover_button').trigger('click');
  });
});

选项2

通过创建一个您要悬停的div并为它提供要调用的网址,来手动编写ajax:

Write the ajax manually by creating a div that you hover and provide it with an url to call:

<div class="some_trigger" data-url="<%= url_for(action: 'get_transfers', section_id: params[:section_id]) %>">Hover me!</div>

绑定到div并进行ajax调用:

Bind to the div and do an ajax call:

$(document).ready(function(){
  $('.some_trigger').hover(function(){
    $.ajax($(this).data('url'));
  });
});

这实际上只会触发操作,而不会对响应执行任何操作.您可以使用以下内容绑定到结果:

This will actually just trigger the action and not perform anything with the response. You can bind to the result with something like this:

$(document).ready(function(){
  $('.some_trigger').hover(function(){
    $.ajax($(this).data('url'))
      .done(function() { alert("success"); })
      .fail(function() { alert("error"); })
      .always(function() { alert("complete"); });
  });
});

有关ajax函数的更多信息,请参见文档.

For more information on ajax function look at the documentation.

这篇关于使用:remote =&gt;悬停事件为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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