如何在rails helper中调用Javascript函数

时间:2022-02-28 16:57:48

I am new to rails. I have created a helper method with a loop. Inside the loop, I want to call a javascript function. Following is the code I have written. Any help would be appreciated. Helper method

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

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

in javascript file test.js

在javascript文件test.js中

function js_function(x1, x2){

}

1 个解决方案

#1


1  

Helper File:

帮助文件:

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

View File:

查看文件:

<%= test_helper SOMEPARAM %>

Will Render HTML (Something Like):

将渲染HTML(类似的东西):

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

#1


1  

Helper File:

帮助文件:

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

View File:

查看文件:

<%= test_helper SOMEPARAM %>

Will Render HTML (Something Like):

将渲染HTML(类似的东西):

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