我有一个与 Cocktail table 显示页面相对应的视图,该页面有一个显示鸡尾酒成分的 div。在视图中,我有一个按钮,单击该按钮应打开一个表单,以在包含成分列表的 div 中添加成分。我已经成功地将 AJAX 应用于成分列表,但是我无法使用按钮隐藏和取消隐藏 div,并且在终端上出现以下错误:
到目前为止,我的代码如下所示:
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 上。我将不胜感激您能提供给我的任何见解。如果您有任何问题,请告诉我。谢谢!
为了能够从“onclick”等属性运行函数,这些函数必须是全局的。
所以你必须将它分配给window
(浏览器中的全局对象):
function addIngredients() {
let ingredient = document.getElementById("ingredients");
if (ingredient.style.display === "none") {
ingredient.style.display = "block";
} else {
ingredient.style.display = "none";
}
}
window.addIngredients = addIngredients;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句