[英]Inserting ERB with JavaScript
我正在尝试使用 JS 将 ERB 元素插入我的页面,但 insertAdjacentHTML 方法不起作用,只是将我的 erb 元素作为字符串
我尝试使用raw
、 .html_safe
和append()
,但这些都不起作用。
这基本上就是我想要做的
btn_plus.addEventListener('click', () => {
btn_plus.insertAdjacentHTML('beforebegin', `<%= select_tag :rg1, options_from_collection_for_select(@users, 'id', 'email') %>`);
})
结果它只是将<%= select_tag:rg1, options_from_collection_for_select(@users, 'id', 'email') %>
作为字符串放在我的页面上
正确的方法是什么?
阿卜杜勒的评论是正确的。 让我详细解释一下 Rails 渲染和 JS 是如何工作的。
When you enter the URL on address bar, say http://url.com/articles/1
, Rails recieves this request and looks for Articles#show
action, then converts the show.html.erb
file to an .html
file(+替换此文件中的动态内容),然后将此 HTML 文件发送到浏览器。 所有这些事情都发生在服务器端。 到目前为止,您在浏览器中的 JS 与它无关。
现在,当您的浏览器收到 HTML(+ CSS 和 JS 文件)时,浏览器将呈现 HTML 文件,它现在将在浏览器中执行 JS。 所以现在你的btn_plus.addEventListener
function 被执行了。 它不会对 rails 部分做任何事情,它只会更新 DOM。 这就是为什么当你在开发工具中检查时你会看到
<%= select_tag :rg1, options_from_collection_for_select(@users, 'id', 'email') %>
而不是看到<select></select>
标记。
你可以做这样的事情。 将您的<%= select_tag:rg1, options_from_collection_for_select(@users, 'id', 'email') %>
包含在.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
});
在.html.erb
文件中,您可以使用 actionview 助手生成如下字符串:
<%= 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
标签。
浏览器中生成的 output 是:
<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文件中使用<select>...</select>
html字符串,可以在.html.erb
文件中声明,稍后在包含的文件中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.