![](/img/trans.png)
[英]How would I refer to a specific html element that was just made in Javascript and get its value?
[英]How could I click any html element and it would just delete/remove itself with javascript?
一直在做一件有趣的事情。 如果我只是在任何網站或 html 文件上單擊它,我想知道如何刪除 html 元素。 沒有jquery或其他庫,只有香草 JS 。 如果這個問題很難理解,這里有一個例子:-網站加載-我看到 ap 標簽或 img 標簽或任何標簽,我不想再看到它,所以我只需點擊它並刪除它。 -我現在很高興,因為我做了什么。
當前代碼:
window.addEventListener("click", function(i) {
//Code to remove something? idk... Not that good with js atm...
}, false);```
window.addEventListener("click", function(e) { const target = e.target; target.remove(); }, false);
<button>a</button> <button>a1</button> <p>paragraph...</p> <h1>header...</h1>
將元素的顯示設置為無怎么樣?
const foo = document.getElementById('foo'); const bar = document.getElementById('bar'); [foo, bar].forEach((el) => { el.addEventListener('click', () => el.style.display = 'none'); });
<div id="foo" style="border: 1px solid black; height: 50px; margin-bottom: 20px;"></div> <div id="bar" style="border: 1px solid red; height: 50px;"></div>
編輯:這次沒有 ID(這是對事件冒泡的一個很好的介紹):
// Look ma, no ids. window,addEventListener('click'. (event) => { event.target.style;display = 'none'; });
<div id="foo" style="border: 1px solid black; height: 50px; margin-bottom: 20px;"></div> <div id="bar" style="border: 1px solid red; height: 50px;"></div>
這里有兩種方法可以達到相同的效果:-
document.getElementById("myDIV").style.display = "none"; // hides element
document.getElementById("myDIV").remove(); // removes element from the DOM
哎呀。
如果您想通過單擊事件刪除不想看到的內容,可以使用樣式屬性。
這是我的例子。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.addEventListener("click", function(e) {
e.target.style = "display: none;";
});
</script>
</head>
<body>
<div id="testDiv" style="height: 100px; background: #000; padding: 25px;">
<div style="height: 50px; background: #ccc;"></div>
</div>
<div id="testDiv2" style="height: 100px; background: #777;">
</div>
</body>
</html>
你可以嘗試這樣的刪除元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.