[英]how to get span element by id?
實際上我創建一個帶有關閉圖標的彈出窗口,我嘗試使用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>
您可以嘗試使用getElementByTagName
或getElementById
而不是類。
或者,嘗試直接在所需span元素的DOM中添加屬性onclick
,然后調用一個能夠執行所需操作的函數。
希望它有所幫助。
我不確定.onclick
來自哪里,但在js元素中不是內聯的js中添加事件是不同的。 比如你不會說
// 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';
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.