美好的一天,
我有三个按钮 - 让我们称之为myBtn1,myBtn2和myBtn3 - 基本上做同样的操作(即在模态模式下打开一个div)。
我有点坚持知道"谁" (即哪个按钮)称为我的javascript。有没有一种简单的方法可以知道或者我是否需要复制我的javascript部分?
对不起,如果这个问题听起来很愚蠢。
非常感谢你的帮助。
干杯
我的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";
}
}
答案 0 :(得分:1)
您可以在事件处理程序中使用event.target
来确定调度事件的对象。这样,您可以轻松地将一个处理程序附加到父级,以处理其所有子级上的事件。
document.getElementById("div").onclick = function(e){
console.log(e.target);
}
&#13;
<div id="div">
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
<button id="btn3">Button 3</button>
</div>
&#13;
答案 1 :(得分:1)
事件侦听器传递一个事件对象。它的target属性是触发事件的元素。
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>
答案 2 :(得分:-1)
<button id="myBtn1" onclick="btnclick(this)">Open Modal</button>
<button id="myBtn2" onclick="btnclick(this)">Open Modal</button>
<button id="myBtn3" onclick="btnclick(this)">Open Modal</button>
在您的javascript
功能中,您可以看到:
function btnclick(ref){
var id = $(ref).attr('id');
}
答案 3 :(得分:-2)
由于您已在HTML文件中使用脚本标记包含js,因此所有js功能和事件都将可用。
//获取打开模态的按钮
var btn = document.getElementById("myBtn");
您的代码中存在错误,您应该提供有效的ID。
var btn = document.getElementById("myBtn1");
//这将有效
现在myBtn1将启动onclick调用
//在你的modal.js
中document.querySelectorAll("button").forEach(function (e) {
e.addEventListener("click", function (event) {
console.log(event.target)
});
});