简体   繁体   English

如何通过id获取span元素?

[英]how to get span element by id?

Actually i create a popup with close icon and i try to close popup form using span method. 实际上我创建一个带有关闭图标的弹出窗口,我尝试使用span方法关闭弹出窗体。 I want to get span element value by element id. 我想通过元素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>

You can try to use getElementByTagName or getElementById instead of by the class. 您可以尝试使用getElementByTagNamegetElementById而不是类。

Alternatively, try to add the attribute onclick directly in the DOM on the wanted span element, and then call a function which does what you want. 或者,尝试直接在所需span元素的DOM中添加属性onclick ,然后调用一个能够执行所需操作的函数。

Hope it helped. 希望它有所帮助。

I'm not sure where the .onclick is coming from but add events in js that are not inline in an html element is different. 我不确定.onclick来自哪里,但在js元素中不是内联的js中添加事件是不同的。 For instance you wouldn't say 比如你不会说

// 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";
}

you would say 你会说

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

if you were using jQuery you could do something like 如果你使用jQuery,你可以做类似的事情

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

or 要么

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

but that just comes down to preference as you can also add the event to the document and specify the target 但这只是归结为首选项,因为您还可以将事件添加到文档并指定目标

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM