首页 > 解决方案 > 在 Rails 6 视图中,如何在隐藏和取消隐藏 div 的按钮上添加事件侦听器?

问题描述

我有一个与鸡尾酒桌显示页面相对应的视图,该页面有一个显示鸡尾酒成分的 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 上。我会很感激你能提供给我的任何见解。如果您有任何问题,请告诉我。谢谢!

标签: javascriptruby-on-railswebpacker

解决方案


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;

推荐阅读