简体   繁体   English

Rails-如何通过AJAX在渲染的部分中调用jQuery事件?

[英]Rails - how to call a jQuery event in a rendered partial through AJAX?

I have this block of code that will display a text after hovering cursor over a DIV: 我有这段代码,将光标悬停在DIV上后将显示文本:

$(document).ready(function() {
  $('.articles').hover(function(){
    $(this).next('.article_details').toggleClass('hidden');
  });
  ...

This is working well. 这运作良好。 But then I have a button for loading another content through partial. 但是然后我有一个按钮,用于通过局部加载另一个内容。 The needed content is loaded well, but the problem is that the jQuery code above doesn't work. 所需的内容加载得很好,但是问题是上面的jQuery代码无法正常工作。

I've tried to put this code 我试图把这段代码

  $('.articles').hover(function(){
    $(this).next('.article_details').toggleClass('hidden');
  });

to the JS file that render new content, like this: 呈现新内容的JS文件,如下所示:

$('.articles').hover(function(){
    $(this).next('.article_details').toggleClass('hidden');
});
$('#show_articles').html("<%= j render(:partial => '/articles/list_of_list_of_articles') %>");

But not even now is the hover event fired. 但是,甚至现在还没有触发hover事件。

I've tried also this: 我也试过这个:

$('.articles').on("hover", function(){
    $(this).next('.article_details').toggleClass('hidden');
});
$('#show_articles').html("<%= j render(:partial => '/articles/list_of_list_of_articles') %>");

but again, no success. 但同样,没有成功。

How to handle this situation? 如何处理这种情况? I am using Rails 4 and jQuery v1.11.1. 我正在使用Rails 4和jQuery v1.11.1。

Thank you in advance. 先感谢您。

The content is inserted dynamically, so you'll need delegated event handlers 内容是动态插入的,因此您需要委托的事件处理程序

$('#show_articles').on({
    mouseenter : function() {
        $(this).next('.article_details').addClass('hidden');
    },
    mouseleave : function() {
        $(this).next('.article_details').removeClass('hidden');
    }
}, '.articles');

You are setting up event handlers before .articles is inserted into page DOM; 您需要在将 .articles插入页面DOM 之前设置事件处理程序; Just try to reverse order of adding the partial content and setting up the hover event, eg 只需尝试颠倒添加部分内容和设置悬停事件的顺序,例如

$('#show_articles').html("<%= j render(:partial => '/articles/list_of_list_of_articles') %>");
$('.articles').hover(function(){
    $(this).next('.article_details').toggleClass('hidden');
});

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

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