再会,
我有三个按钮 - 让我们称它们为 myBtn1、myBtn2 和 myBtn3 - 执行基本相同的操作(即在模态模式下打开 div)。
我有点不知道“谁”(即哪个按钮)调用了我的 javascript。有没有一种简单的方法可以知道这一点,或者我是否需要复制我的 javascript 部分?
抱歉,如果这个问题听起来很愚蠢。
非常感谢你的帮助。
Cheers
我的html代码:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/test.css" />
</head>
<body>
<!-- Trigger/Open The Modal -->
<button id="myBtn1">Open Modal</button>
<button id="myBtn2">Open Modal</button>
<button id="myBtn3">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal... </p>
<p>Called by [myBtn1 or myBtn2 or myBtn3] </p>
</div>
<script type="text/javascript" src="./scripts/modal.js"></script>
</div>
</body>
</html>
我的JavaScript(modal.js):
/*
modal.js
*/
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
向事件侦听器传递一个事件对象。它的目标属性是触发事件的元素。
document.querySelectorAll("button").forEach(function (e) {
e.addEventListener("click", function (event) {
console.log(event.target)
});
});
<div>
<button id="button1">Button 1</button>
<button id="button2">Button 2</button>
<button id="button3">Button 3</button>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)