用Javascript创建一个函数,并将其与按钮一起使用



我正试图让这个按钮运行函数。我知道我可以在Javascript中去掉"函数showWeb",代码会运行得很好,我正在努力让它发挥作用,这样我就可以把它用作函数,这样我就能创建对象的实例。

<button id='myBtn' onclick='showWeb()'>Open Modal</button>
<div id='myModal' class='modal'>
<div class='modal-content'>
<span class='close'>&times;</span>
<p>$link</p>
</div>
</div>      

<script>
function showWeb(){
// 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 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";
}
}
}
</script>

我不确定你想做什么,但请考虑function必须只做一项任务,如果你以这种方式重构代码,那就太好了。

function openModal() {
var modal = document.getElementById('myModal');
modal.style.display = "block";
}
function closeModal() {
var modal = document.getElementById('myModal');
modal.style.display = "none";
}
window.onclick = function(event) {
var modal = document.getElementById('myModal');
if (event.target == modal) {
modal.style.display = "none";
}
}
<button id='myBtn' onclick='openModal()'>Open Modal</button>
<div id='myModal' class='modal'>
<div class='modal-content'>
<span class='close' onclick='closeModal()'>&times;</span>
<p>$link</p>
</div>
</div>

首先,您不想在函数中检索按钮。其次,那些onclick事件没有正确附加(在这种情况下是打字错误(

你想做的是:

var modal = document.getElementById('myModal');
var btn = document.getElementById('myBtn');
var span = document.getElementsByClassName('close')[0];
btn.addEventListener('click', showModal());
span.addEventListener('click', hideModal());
function showModal() {
modal.style.display = 'block';
};
function hideModal() {
modal.style.display = 'none';
};
window.addEventListener('click', function(event) {
if (event.target != modal) { // needs to be anything but the modal, from what i can understand
hideModal();
}
});
#myModal {
display: none;
background: #dd4535;
}
<button id='myBtn'>Open Modal</button>
<div id='myModal' class='modal'>
<div class='modal-content'>
<span class='close'>&times;</span>
<p>$link</p>
</div>
</div>

这次没有jquery,因为它显然没有被很好地接受。纯JS

相关内容

最新更新