繁体   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