javascript - 在 Rails 6 视图中,如何在隐藏和取消隐藏 div 的按钮上添加事件侦听器?
问题描述
我有一个与鸡尾酒桌显示页面相对应的视图,该页面有一个显示鸡尾酒成分的 div。在视图中,我有一个按钮,单击该按钮应打开一个表单以在包含成分列表的 div 中添加成分。我已经成功地将 AJAX 应用于成分列表,但是我无法使用按钮隐藏和取消隐藏 div,并且在终端上出现以下错误:
- 未捕获的 ReferenceError:addIngredients 未在 HTMLButtonElement.onclick 中定义 (17:26)
到目前为止,我的代码如下所示:
function addIngredients() {
let ingredient = document.getElementById("ingredients");
if (ingredient.style.display === "none") {
ingredient.style.display = "block";
} else {
ingredient.style.display = "none";
}
}
<body>
<div class="container-fluid">
<div class="row">
<div class="col-6 section" id="cocktail">
<h1><%= @cocktail.name%></h1>
<%= cl_image_tag @cocktail.photo.key, height: 300, width: 400, crop: :fill %>
<% if @cocktail.ingredients.blank? %>
Please add the ingredients <%= @cocktail.name %>
<% else %>
<% @cocktail.ingredients.each do |ingredient| %>
<p><%= ingredient.name %>:<%=ingredient.quantity %> <%=ingredient.unit%></p>
<% end %>
<% end %>
<button class="btn btn-light btn-lg"><%= link_to "Cocktail List", cocktails_path %></button>
<button class="btn btn-dark btn-lg" onclick="addIngredients()">Add Ingredients</button>
</div>
<div class="col-6 section" id="ingredients">
<h2>Ingredients</h2>
<%= simple_form_for([ @cocktail, @ingredient ], remote: true) do |f| %>
<%= f.input :name %>
<%= f.input :quantity %>
<%= f.input :unit %>
<%= f.button :submit %>
<% end %>
</div>
</div>
</div>
<%= javascript_pack_tag 'cocktails-show' %>
</body>
我输入的代码似乎只适用于堆栈溢出,所以我猜测问题可能出在 webpacker 上。我会很感激你能提供给我的任何见解。如果您有任何问题,请告诉我。谢谢!
解决方案
To be able to run functions from attributes like 'onclick', the functions must be global.
So you have to assign it to window
(which is the global object in the browser):
function addIngredients() {
let ingredient = document.getElementById("ingredients");
if (ingredient.style.display === "none") {
ingredient.style.display = "block";
} else {
ingredient.style.display = "none";
}
}
window.addIngredients = addIngredients;
推荐阅读
- c - 为什么 qemu 有时会比 ptrace 计数更多有时更少的指令?
- qt - 在 Qwt 图中使用一对一标签
- python - 如何在 2d 列表 python 中找到具有相同变量的值的总和,仅使用列表理解?
- haskell - 在模式匹配的不同情况下推导出不同的类型类约束
- javascript - 如何处理由崩溃导致的 404 页面返回。反应路由器
- swift - 停止在 UITableView 的嵌套 UICollectionView 中播放视频或仅在嵌套结构中的可见单元格上播放
- svelte - Svelte (rollup) - 错误:意外的令牌(请注意,您需要 @rollup/plugin-json 来导入 JSON 文件)
- datetime - 如果 yaxis 包含空 dateTime 数据并且 useUTC 为 false,则图表未呈现并引发脚本错误
- r - 在运行时为克隆的元素创建 R 闪亮绑定?
- html - Shopify - 具有单独样式的重复块