[英]How does one remove a button element from the DOM after it was clicked?
我想讓我的按鈕在點擊時自行刪除,我已經嘗試過了:
var myArray = ['JavaScript is awesome', 'Pacific coffe is really delicious', 'This is a fancy website']; var rand = Math.floor(Math.random() * myArray.length); var button = document.getElementsByClassName("newQuote"); function showquote() { console.log(document.getElementsByClassName("quote").innerHTML = myArray[rand]); button.remove(); };
<:DOCTYPE html> <html lang="en"> <head></head> <p class="quote"></p> <button class="newQuote" onclick="showquote()">Generate Quote</button> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </body> <script src="main.js"></script>
仍然沒有任何效果,請幫助
button
是一個數組,只需寫button[0].remove();
var myArray = ['JavaScript is awesome', 'Pacific coffe is really delicious', 'This is a fancy website']; var rand = Math.floor(Math.random() * myArray.length); var button = document.getElementsByClassName("newQuote"); function showquote(){ console.log(document.getElementsByClassName("newQuote").innerHTML = myArray[rand]); button[0].remove() };
<:DOCTYPE html> <html lang="en"> <head></head> <p class="quote"></p> <button class ="newQuote"onclick="showquote()">Generate Quote</button> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </body> <script src="main.js"></script> </html>
.remove()
是一種 jQuery 方法。 但是您正在使用香草 Javascript ( document.getElementsByClassName("newQuote")
)選擇您的按鈕,因此它沒有任何 jQuery 方法。 此外, getElementsByClassName
返回一個元素列表,而不是一個元素,因此您必須迭代它們。
解決方案:使用 jQuery 到 select 您的按鈕。
另外,為什么要使用內聯 JS( onclick="showquote()"
)? 使用 jQuery 點擊處理程序。
var button = $(".newQuote"); button.click(showquote); function showquote() { button.remove(); };
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <p class="quote"></p> <button class="newQuote">Generate Quote</button>
OP remove
按鈕的主要問題是......
button = document.getElementsByClassName("newQuote");
...不會將HTMLElement
分配給button
,而是HTMLCollection
...看看getElementsByClassName
。
人們可能會考慮使用一種更簡單或更通用的方式來訪問確實觸發了某個事件的元素。
一種可靠的方法是通過addEventListener
注冊事件,而不是依賴於 OP 的原始內聯事件處理。 然后使用事件處理程序的Event
object的currentTarget
或使用處理程序的this
上下文,它也表示觸發事件目標。
var myArray = [ 'JavaScript is awesome', 'Pacific coffe is really delicious', 'This is a fancy website', ]; function addQuote(evt) { const btnElm = evt.currentTarget; //const btnElm = this; // this variant is equally fine. document.querySelector('.quote').textContent += ' - ' + myArray[ Math.floor(Math.random() * myArray.length) ]; btnElm.remove(); }; function init() { document.querySelectorAll('.newQuote').forEach(elmNode => elmNode.addEventListener('click', addQuote) ); } init();
<button class ="newQuote">Generate a quote</button> <button class ="newQuote">Generate another quote</button> <button class ="newQuote">Generate yet another quote</button> <p class="quote"></p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.