我有一個對應于雞尾酒表展示頁面的視圖,其中有一個顯示雞尾酒成分的div。在該視圖中,我有一個按鈕,點擊后應打開一個表單,在包含成分串列的div中添加成分。我已經成功地對配料表應用了AJAX,但我在隱藏和取消隱藏帶有按鈕的div時遇到了麻煩,我在終端上得到了以下錯誤:
- 未發現參考錯誤:addIngredients未被定義 at 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>/span>
<div class="container-fluid"/span>>
<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? %>
請添加配料 <%= @cocktail.name %>
<% else %>
<% @cocktail. ingredients.each do |ingredient| %>
<p><%= ingredient.name %> :<%=ingredient. 數量%><%=成分.單位%></p><%=成分.單位%>p>
<% end %>
<%結束%>
<button class="btn btn-light btn-lg"/span>> <%= link_to "Cocktail List", cocktails_path %></button>
< button class="btn btn-dark btn-lg" onclick="addIngredients()" > 添加成分</按鈕>
</div>/span>
< 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>/span>
</div>/span>
<%=JavaScript_pack_tag 'cocktails-show' %>
</body>/span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
我輸入的代碼似乎只在stack overflow上作業,所以我猜測問題可能出在webpacker上。如果你能提供給我任何見解,我將非常感激。如果你有任何問題,請讓我知道。謝謝你!
uj5u.com熱心網友回復:
為了能夠從 "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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322771.html
標籤:
