如何只删除在jquery中使用append()追加的标签

时间:2009-08-03 04:45:52

标签: jquery tags append

我有一个div在鼠标上弹出,我使用html()插入一些内容。我希望代码的某些部分能够保持不受操纵。

<div id="pop_div" ><span>X</span></div>


$("#team_div > ul img").bind('mouseenter',function(){
  $("#pop_div").html('<img src="' + img + '"/>' + content );
 });

和onclick我隐藏了div。

$('#pop_div span').click(function(){
  $("#pop_div").hide();
});

我的问题是,我无法使用下面的代码,因为jquery没有为该标签分配任何事件

$("#pop_div").html('<span>X</span><img src="' + img + '"/>' + content );

(我不能使用livequery插件)

感谢您的评论。

2 个答案:

答案 0 :(得分:1)

您正在替换#pop_div的整个内容,当您插入HTML代码时,正在创建新的DOM元素,这就是事件没有绑定的原因。

从DOM中删除span元素,并且附加到它的事件不再有效。

我认为您不需要替换该div的所有内容,您可以像这样构建您的div:

<div id="pop_div" >
  <span>X</span>
  <img/>
  <div id="content"></div>
</div>

在您的鼠标中心:

$('#team_div > ul img').bind('mouseenter',function(){
  $('#pop_div img').attr('src', img); // set the image source
  $('#pop_div #content').html(content); // display the content
});

图片来源已更改,content变量已插入'#content' div。

您的点击处理程序将保持现状,因为span元素不受影响。

答案 1 :(得分:1)

CMS是对的。从jQuery 1.3开始,你可以绑定你的事件with the live function,它将事件绑定到所有当前和未来的元素。

$('#team_div > ul img').live('mouseenter',function(){
  $('#pop_div img').attr('src', img); // set the image source
  $('#pop_div #content').html(content); // display the content
});