【问题标题】:Inserting ERB with JavaScript使用 JavaScript 插入 ERB
【发布时间】:2019-09-23 15:38:46
【问题描述】:

我正在尝试使用 JS 将 ERB 元素插入到我的页面中,但是 insertAdjacentHTML 方法不起作用,只是将我的 erb 元素作为字符串放置

我尝试使用raw.html_safeappend(),但这些都不起作用。

这基本上就是我想做的事情

btn_plus.addEventListener('click', () => {
    btn_plus.insertAdjacentHTML('beforebegin', `<%= select_tag :rg1, options_from_collection_for_select(@users, 'id', 'email') %>`);
  })

因此它只是将&lt;%= select_tag :rg1, options_from_collection_for_select(@users, 'id', 'email') %&gt; 作为字符串放在我的页面上

正确的做法是什么?

【问题讨论】:

  • rails 标签在服务器端转换为 html,所以它在 js 文件中不起作用,因为它将在客户端运行

标签: javascript ruby-on-rails erb


【解决方案1】:

.html.erb 文件中,您可以使用actionview helper 生成这样的字符串:

<%= javascript_tag do %>
    const foo = '<%= select_tag(:foo, raw("<option>bar</option><option>baz</option>")) %>'
    $('#put_it_here').append(foo)
<% end %>

您也可以使用options_for_select,但我没有任何方便的工具来检查它,所以我的示例仅使用原始options 标签。

浏览器中的结果输出是:

<script>
//<![CDATA[

  const foo = '<select name="foo" id="foo"><option>bish</option><option>bash</option></select>'
  $('#put_it_here').append(foo)

//]]>
</script>

你可以在你的 javascript 表达式中使用字符串 'foo' 将它动态插入到你想要的位置,我在这里使用了 jQuery。

如果需要在包含的js文件中使用&lt;select&gt;...&lt;/select&gt;html字符串,可以在.html.erb文件中声明,稍后在包含的文件中使用。

【讨论】:

    【解决方案2】:

    阿卜杜勒的评论是正确的。让我详细解释一下 Rails 渲染和 JS 的工作原理。

    当你在地址栏输入 URL,比如 http://url.com/articles/1,Rails 收到这个请求并寻找 Articles#show 动作,然后将 show.html.erb 文件转换为 .html 文件(+ 替换这个文件中的动态内容) 然后将此 HTML 文件发送到浏览器。所有这些事情都发生在服务器端。你在浏览器中的 JS 到现在都与它无关。

    现在,当您的浏览器接收 HTML(+ CSS 和 JS 文件)时,浏览器将呈现 HTML 文件,现在它将在浏览器中执行 JS。所以现在你的btn_plus.addEventListener 函数被执行了。它不会对 rails 部分做任何事情,它只会更新 DOM。这就是为什么当您在开发工具中检查时会看到

    <%= select_tag :rg1, options_from_collection_for_select(@users, 'id', 'email') %>
    

    而不是看到&lt;select&gt;&lt;/select&gt; 标签。

    你可以做这样的事情。将您的&lt;%= select_tag :rg1, options_from_collection_for_select(@users, 'id', 'email') %&gt; 包含在您的.html.erb 文件中您想要的任何位置。然后在你的 JS 中,你可以这样做:

    const rg1 = document.getElementById('rg1');
    const btn_plus = document.getElementById('btn_plus'); // change your ID here if it's different
    
    // Hide the select tag
    rg1.style.display = 'none';
    
    // On btn click, show the select tag:
    btn_plus.addEventListener('click', () => {
      rg1.style.display = 'inline-block'; // or `block` or anything you want
    });
    

    【讨论】:

    • 感谢您的解释!其实我想过隐藏/显示的方法,但是我想在用户每次点击按钮时添加一个新的select
    • 好的,我想你可以做一些类似于 Les's Answer 的事情。创建一个动态的javascript_tag 并在用户每次点击按钮时附加它。
    • 是的,它奏效了。再次感谢您为我澄清!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多