0
当我的JavaScript代码是相同的HTML页面,事件侦听器工作:事件侦听外部文件不工作
.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);
z-index: 1;
}
/* 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;}
<div class="dropdown">
\t \t <button id="dropBtn" class="dropbtn">Dropdown</button>
\t \t \t <div id="myDropdown" class="dropdown-content">
\t \t \t <a href="#">Link 1</a>
\t \t \t <a href="#">Link 2</a>
\t \t \t <a href="#">Link 3</a>
\t \t \t </div>
\t </div>
<script>
\t \t
\t \t var dropdown = document.getElementById("dropBtn");
\t \t
\t \t function myFunction() {
\t \t document.getElementById("myDropdown").classList.toggle("show");
\t \t }
\t \t
\t \t dropdown.addEventListener("click", myFunction, false);
\t \t
\t \t // Close the dropdown menu if the user clicks outside of it
\t \t window.onclick = function(event) {
\t \t if (!event.target.matches('.dropbtn')) {
\t \t
\t \t var dropdowns = document.getElementsByClassName("dropdown-content");
\t \t var i;
\t \t for (i = 0; i < dropdowns.length; i++) {
\t \t var openDropdown = dropdowns[i];
\t \t if (openDropdown.classList.contains('show')) {
\t \t openDropdown.classList.remove('show');
\t \t }
\t \t }
\t \t }
\t \t }
\t
</script>
但是当我把相同的JavaScript代码放到外部JS文件,事件监听器不工作。
我包括JS文件刚刚闭幕</body>
标记之前:
<script type="text/javascript" src="js/main.js"></script>
</body>
如何让我的事件监听器从外部文件中的作品,不只是里面的HTML页面?
当您在外部包含脚本时,在控制台中是否出现错误? –
您的JavaScript不失败,因为它在它自己的文件中。你的文件路径是否正确? –
为了测试目的我把:window.onload = function(){ alert('Hello World!'); }在main.js文件中.....它在我的index.html上工作,但不在其他HTML文件中。 – Nemus