如何删除用jQuery创建的元素? [英] how to delete element created with jquery?

查看:61
本文介绍了如何删除用jQuery创建的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已在jquery中编写此代码块,以在发生某些事件后创建三个元素

i have write this block of code in jquery to create three element after some events

$('body').append(
tmp= $('<div id="tmp"></div>')
);

$('<div id="close" />').appendTo("#tmp");   
$('<div id="box-results" />').appendTo('#tmp');

这三个元素是正常创建的,并已添加到我的DOM中,但我想使用以下功能将其删除:

this three elements are created normally and added to my DOM but i want to remove them with some function like this :

$("#close").click(function(e){

e.preventDefault();
$("#tmp").remove(); 
//$("#overlay").remove(); 
});

在我单击关闭后,div会发生!我的代码有什么问题?

and after i click close div noting happen ! what's wrong with my code ?

这是在线示例: mymagazine.ir/index.php/main/detail/36 -因为站点语言是波斯语,所以请在站点中找到这是jquery问题"一句话

here is online example : mymagazine.ir/index.php/main/detail/36 - please find " here is jquery issue" sentence in site because site language is Persian

推荐答案

将元素插入文档后,您需要在#close 上添加点击处理程序.

you need to add the click handler on #close after you insert the element into the document.

编辑提供所需的演示;在ff36中进行了测试:

edit providing the requested demo; tested in ff36:

<html>
<head>
 <title>whatever</title>
 <style type="text/css">
   div {
     border: 1px solid black;
     padding: 0.3em;
   }
 </style>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
 <script type="text/javascript">
  $(document).ready(function ()
  {
    $('body').append($('<div id="tmp"/>'));
    $('<div id="close">click me</div>').appendTo("#tmp");   
    $('<div id="box-results">contents</div>').appendTo('#tmp');
    $('#close').bind('click', function ()
    {
      $('#tmp').remove();
      return false;
    });
  });
 </script>
</head>
<body>
</body>
</html>

修改

更改插件的代码

$.ajax({
    ...
    success: function ()
    {
        $('<div id="close"/>').appendTo($('#tmp'));
    }
});
$('#close').click(function (e) ...);

$.ajax({
    ...
    success: function ()
    {
        $('<div id="close"/>')
            .click(function (e) ...)
            .appendTo($('#tmp'))
        ;
    }
});

这篇关于如何删除用jQuery创建的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆