简体   繁体   English

使用jQuery删除附加的html?

[英]Removing appended html using jQuery?

Using jquery, I currently append html to a div on a click event. 使用jquery,我目前在点击事件上将html附加到div。 The following code allows me to fade in only the appended portion of the div: 以下代码允许我仅淡入div的附加部分:

var html = "..";
$('<div></div>').appendTo("#id").hide().append(html).fadeIn('slow');

This portion works perfectly. 这部分完美无缺。 But how can I later remove (fade out) only the appended portion? 但是我怎么能在以后删除(淡出)附加部分呢? I tried hacking this by storing the html prior to the appending, and then simply hiding everything and showing the stored html. 我尝试通过在追加之前存储html来隐藏它,然后简单地隐藏所有内容并显示存储的html。 But this does not work well when the same procedure is reused for several divs on the same page (and this seems like poor implementation). 但是,当在同一页面上为几个div重用相同的过程时,这不能很好地工作(这看起来很糟糕)。 Is there a good way to do this? 有没有办法做到这一点?

Just to give an idea of why I need this: Think of a blog type page where for every article on the page there are several comments with only x amount showing by default: the click event fetches the remaining comments and displays them, and then toggling the button again removes the appended comments and sends it back to the original state. 只是想知道为什么我需要这个:想想一个博客类型的页面,页面上的每篇文章都有几个注释,默认情况下只显示x个数量:click事件获取剩余的注释并显示它们,然后切换该按钮再次删除附加的注释并将其发送回原始状态。

empty() is always an option empty()始终是一个选项

jQuery('#main').empty(); jQuery的( '#主')空();

I'd just set and clear the html with '.html()' ... 我只是用'.html()'来设置和清除html ...

-- edit - 编辑

to be more clear, have an area layed out specifically for the addition of these comments: 更清楚的是,有一个专门用于增加这些评论的领域:

<div id='commentarea1'></div>

etc. 等等

Give a look at the empty() function. 看一下empty()函数。

It might better solve the problem. 它可能更好地解决问题。 Here's the link http://api.jquery.com/empty/ 这是链接http://api.jquery.com/empty/

Try: 尝试:

var html = "..";
$('<div></div>').appendTo("#id").hide().append(html).fadeIn('slow').addClass('appended');

then later 然后

$('#id .appended').fadeOut('slow'); // or whatever you want to do.

It is not that clear from the question but say you show 5 comments by default and then show x more comments. 问题并不是那么清楚,而是说你默认显示5条评论,然后再显示x条评论。 To get back to the original 5 comment default state you can remove all comments with an index greater than 4 (zero based). 要返回到原始5注释默认状态,您可以删除索引大于4(基于零)的所有注释。

The following assumes each comment goes inside its own div that has a class comment. 以下假设每个注释都在其自己的具有类注释的div中。

$('#id>div.comment:gt(4)').remove();

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

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