如何通过id获取span元素?

时间:2019-05-05 10:34:15

标签: javascript php html

实际上,我创建了一个带有关闭图标的弹出窗口,我尝试使用span方法关闭弹出窗口。我想按元素ID获取span元素的值。

       <script>
  // 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")[1];

  // 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 :(得分:0)

您可以尝试使用getElementByTagNamegetElementById来代替班级。

或者,尝试将属性onclick直接添加到DOM中所需的span元素上,然后调用执行所需功能的函数。

希望有帮助。

答案 1 :(得分:0)

我不确定.onclick的来源,但是在js元素中不是在html元素中内联的添加事件是否有所不同。例如,你不会说

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

你会说

btn.addEventListener('click', function() {
    modal.style.display = 'block';
});

如果您使用的是jQuery,则可以执行类似的操作

$('#myBtn').click(function() {
    modal.style.display = 'block';
});

$('#myBtn').on('click', function() {
    modal.style.display = 'block';
});

但这只是优先考虑,因为您还可以将事件添加到文档中并指定目标

$(document).on('click', '#myBtn', function() {
    modal.style.display = 'block';
});
相关问题