簡體   English   中英

如何在 JQuery 中收聽偶數,具體來說,在按鈕后添加 ap 元素並添加單擊時再次刪除它的功能

[英]How to listen to an even in JQuery, specifically, add a p element after a button and add the ability to remove it again on click

在這段代碼中,我必須通過單擊按鈕添加 ap 元素,使元素出現在按鈕之后(按鈕下方的行)。 然后我必須能夠通過單擊這個新出現的段落中的任何單詞再次刪除 p。 任何幫助將不勝感激,謝謝!

 $(document).ready(function(){ $("#btn").click(function(){ $("#btn").after(" <br/r> " + "Click on me to remove"); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <p class="test">Test 5: Listen for Event</p> <p>This is a paragraph.</p> <p>Click on the button below to insert a new paragraph after this and add the ability to remove the paragraph when it is clicked.</p> <p><button id="btn">Insert a new p element after this button</button></p> </div>

您可以使用 css 選擇器〜確保僅在按鈕后定位p 然后只需將事件處理程序添加到#btn ~ p

其中最重要的部分是事件委托。 通過將事件委托給document (或父級),您可以捕獲所有未來添加到 dom 的P元素。 在沒有委托的情況下,事件處理程序在添加事件處理程序時僅與 DOM 中的元素相關聯。

 $(document).ready(function(){ $("#btn").click(function(){ $("#btn").after("<p>Click on me to remove</p>"); }); $(document).on("click","#btn~p",function(){ $(this).remove(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <p class="test">Test 5: Listen for Event</p> <p>This is a paragraph.</p> <p>Click on the button below to insert a new paragraph after this and add the ability to remove the paragraph when it is clicked.</p> <p><button id="btn">Insert a new p element after this button</button></p> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM