简体   繁体   English

创建“删除div”链接

[英]Create a 'remove div' link

With this code I'm able to add a div with some text and and hyperlink inside the div: 使用此代码,我可以在div中添加带有一些文本和超链接的div:

$('<div/>')
    .html("<a href='#'>x</a> " + i.item.label + " - ")
    .attr({ 'id': i.item.val })
    .addClass('boxClass')
    .appendTo('#acResults');

I'd like to remove the created link when I click on the x link inside the created div. 当我点击创建的div中的x链接时,我想删除创建的链接。 Something similar to the remove tag in the tags section of this site. 与此站点的tags部分中的remove标记类似的内容。

Could you please help me? 请你帮助我好吗?

Because the element is appended dynamically you would need to use a delegated event handler. 因为元素是动态附加的,所以需要使用委托的事件处理程序。 From there you can use closest() to find the parent div and remove it. 从那里你可以使用closest()来找到父div并将其删除。 Try this: 尝试这个:

$('#acResults').on('click', '.boxClass a', function(e) {
    e.preventDefault();
    $(this).closest('.boxClass').remove();
});

You can do this : add click event using .on() (we do it for dynamically created element) and use .remove() to remove clicked link. 您可以这样做:使用.on()添加click事件(我们为动态创建的元素执行此操作)并使用.remove()删除单击的链接。

$(document).on('click','div.boxClass a',function(){
    $(this).remove();
});

EDIT - as OP mentioned "I'd like to remove the created link when I click on the x link inside the created div" in the post, but it looks like OP want to remove div and not the link. 编辑 - 正如OP提到的“我想在帖子中点击创建的div中的x链接时删除创建的链接”,但看起来OP想要删除div而不是链接。 Please find below updated answer - 请在下面找到更新的答案 -

$(document).on('click','div.boxClass a',function(){
     $(this).closest('div.boxClass').remove();
 });

add some class to this link 在此链接中添加一些类

$('<div/>')
  .html("<a class='remove-link' href='#'>x</a> " + i.item.label + " - ")
  .attr({'id': i.item.val})
  .addClass('boxClass')
  .appendTo('#acResults');

and then try 然后试试

$('.remove-link').click(function (event) {
   event.preventDefault();
   $(this).remove();
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM