用Javascript创建函数并与按钮一起使用

时间:2018-12-06 03:41:56

标签: javascript html

我正在尝试使该按钮运行该功能。我知道我可以摆脱Javascript中的“函数showWeb”,并且代码可以正常运行,我正在尝试使其正常运行,以便可以将其用作函数,以便创建对象的实例。 / p>

<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>

2 个答案:

答案 0 :(得分:1)

我不确定您要达到的目标,但是请考虑一下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>  

答案 1 :(得分:-1)

首先,您不想在函数内 中检索按钮。 其次,那些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