如何在 rails 助手中调用 Javascript 函数

How to call a Javascript function in rails helper

我是 rails 的新手。我创建了一个带循环的辅助方法。在循环内部,我想调用一个 javascript 函数。以下是我编写的代码。任何帮助,将不胜感激。 辅助方法

def test_helper param1
   param1.each do |x|
     "js_function(x.col1, x.col2)"
   end
end

在 javascript 文件中 test.js

function js_function(x1, x2){

}

帮助文件:

def test_helper param1
  javascript_tag(
    param1.map do |x|
      "js_function(\"#{j raw(x.col1)}\", \"#{j raw(x.col2)})\";"
    end.join("\n")
  )
end

查看文件:

<%= test_helper SOMEPARAM %>

将渲染 HTML(类似于):

<script>
  js_function(SOMEVALUEA1, SOMEVALUEA2);
  js_function(SOMEVALUEB1, SOMEVALUEB2);
</script>