简体   繁体   English

Rails中ajax调用后调用js文件

[英]Call a js file after ajax call in Rails

I am using prismjs for syntax highlighting in my Rails app.我在 Rails 应用程序中使用prismjs进行语法高亮显示。 I have included the stylesheet and js file in my layout.我已经在我的布局中包含了样式表和 js 文件。 My problem is that code is highlighted only once on page load.我的问题是代码在页面加载时只突出显示一次。 Whenever the partial refreshes after an ajax call, the code highlight does not work.每当 ajax 调用后局部刷新时,代码高亮就不起作用。 If I include the prismjs file in partial then it works.如果我包含部分的prismjs 文件,那么它就可以工作。 Is there any better way to make this work?有没有更好的方法来完成这项工作?

layout.html.erb布局.html.erb

<%= stylesheet_link_tag :prism %>
<%= javascript_include_tag :prism %>

This works on page load for the first time.这是第一次在页面加载时起作用。 Then to make it work on every ajax call response I must do this:然后为了让它在每个 ajax 调用响应上工作,我必须这样做:

partial.html.erb部分.html.erb

<%= javascript_include_tag :prism %>

Is there any other better way to achieve the same like call this file from a customevent or any other method?有没有其他更好的方法可以实现相同的目标,例如从自定义事件或任何其他方法调用此文件?

If you update your HTML either with HTML response from the Ajax call or from JSON updating the HTML.如果您使用来自 Ajax 调用的 HTML 响应或从更新 HTML 的 JSON 更新您的 HTML。 The content of that part of the page gets changed and the effect on PrismJS being loaded on the page load goes away, so you need to call it again for the highlight to work.页面该部分的内容被更改,对页面加载时加载的 PrismJS 的影响消失,因此您需要再次调用它以使突出显示工作。

Here are the methods you will need for this.以下是您需要的方法。 Once you update the HTML just call either highlightAll or highlightAllUnder if you want to be more localized in your update.更新 HTML 后,如果您想在更新中更加本地化,​​只需调用highlightAllhighlightAllUnder即可。

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

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