在js.erb Ruby on Rails中渲染部分后,资产中的Javascript无法正常工作

时间:2022-05-20 19:06:36

Question similar to mine are asked before but here the scenario is bit different - I have a js.erb file in which I'm publishing using (private_pub) a partial like below

之前问过类似于我的问题,但这里的情况有点不同 - 我有一个js.erb文件,我在其中使用(private_pub)发布部分如下所示

<% publish_to "/conversation/update_waiter" do %>
   $("#online_waiters").replace_html('<%= j(render :partial => "/restaurants/online_waiters")%>');     
<% end %>

the partial is rendered on all users wall successfully and no extra or duplicate divs are generated . But on click function (which is an anchor in newly rendered partial) stops working . While its functionality is defined in /assets/js . Now after showing that partial on users if i refresh the page , then the same partial which is displayed due to my cookies , works fine . Any help or idea will be appreciated

部分在所有用户墙上成功呈现,不会生成额外或重复的div。但是在点击功能(这是新渲染的部分中的锚点)停止工作。虽然它的功能在/ assets / js中定义。现在,如果我刷新页面显示部分用户,那么由于我的cookie显示相同的部分,工作正常。任何帮助或想法将不胜感激

1 个解决方案

#1


4  

Attach the click handler to a parent element of the generated elements and it will work on all generated elements from partials.

将单击处理程序附加到生成的元素的父元素,它将处理来自partials的所有生成元素。

Say you have a div with class content which contains all your html.

假设您有一个包含所有html的类内容的div。

$(".content").on("click", "#anchor_one", function(e) {
  console.log("Working!");
});

Or attach it to the document

或将其附加到文档

$(document).on("click", "#anchor_one", function(e) {
  console.log("Working!");
});

Another solution is to add the handler inside your js.erb file.

另一种解决方案是在js.erb文件中添加处理程序。

#1


4  

Attach the click handler to a parent element of the generated elements and it will work on all generated elements from partials.

将单击处理程序附加到生成的元素的父元素,它将处理来自partials的所有生成元素。

Say you have a div with class content which contains all your html.

假设您有一个包含所有html的类内容的div。

$(".content").on("click", "#anchor_one", function(e) {
  console.log("Working!");
});

Or attach it to the document

或将其附加到文档

$(document).on("click", "#anchor_one", function(e) {
  console.log("Working!");
});

Another solution is to add the handler inside your js.erb file.

另一种解决方案是在js.erb文件中添加处理程序。