[英]Linking a Javascript function on a layout that is loaded from the asset pipeline in ruby on rails?
當檢查時從靜態頁面布局中的資產管道加載的javascript文件(app / assets / javacripts / bootstrap.js)鏈接函數時,我得到:未捕獲的ReferenceError:未定義myFunction。 我已經搜索了幾個小時,並且沒有使用ruby內部的Coffeescript或Jquery或方法,我只是想將此函數從我的.js文件鏈接到視圖中的布局中。 任何具體的解釋,或者您是否可以將我鏈接到有關如何執行此操作的任何資源...,或者是旨在將Javascript快速鏈接到視圖而不會打擾管道的教程,這些都是很好的。 先感謝您。
這是Javascript函數:
/* When the user clicks on the button,
toggle between hiding and showing dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i=0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
這是對應的CSS:
/* Dropdown Button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}
/* Show the dropdown menu (use JS to add this class to the .dropdown- content container when the user clicks on the dropdown button) */
.show {display:block;}
這是我的html:
<li>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#work_places">Work Places</a>
<a href="#living_places">Living Places</a>
<a href="#learning_places">Learning Places</a>
<a href="#interiors">Interiors</a>
<a href="#miscellaneous">Miscellaneous</a>
</div>
</div>
</li>
嘗試以這種方式定義函數,以(希望)使其在您的視圖中全局且可訪問:
this.myFunction = function() {
document.getElementById('myDropdown').classList.toggle('show');
};
否則,您可以從視圖中刪除onclick並將其附加到javascript文件中:
document.getElementsByClassName('dropbtn')[0].onclick = function() {
document.getElementById('myDropdown').classList.toggle('show');
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.