jquery删除变量内的html元素(jquery对象)

在HTML内部我有这个DIV:


// usually one thumb image; can be up to three some text goes here, sometimes not
always a link here
and sometimes another line here

我需要捕获DIV的内容减去变量中的第一行(拇指),以作为标题(标题)传递给灯箱脚本。 然而,在一天我学到了关于javascript和jquery的东西(两者都是我的弱点),但是我通过搜索网络找到的东西,包括stackoverflow上的几个线程,没有做到这一点,无论是抛出错误还是仍然包括拇指或删除文本,甚至从DOM中删除拇指:

 // takes the whole var teaser = $(".teaser"); // TypeError: $(...).html(...).find is not a function var teaser = $(".teaser").find("img").remove(); // IMGs removed from DOM var teaser = $(".teaser").find("img").remove(); // IMGs still included; I think I understand why var teaser = $(".teaser").not("img"); // ditto var teaser = $(".teaser").clone().not("img"); // ditto: var teaser = $(".teaser"); $(teaser).find("img").remove(); // no teaser at all (everything removed, not just the IMGs) var teaser = $(".teaser"); teaser = $(teaser).find("img").remove(); // ditto var teaser = $(".teaser").clone().find("img").remove(); 

改变链接的顺序也不起作用(虽然我可能错过了一个或另一个)。

这种解决方法似乎没问题:

 var teaser = $(".teaser").html().replace(/(<img.*?)+
]*?/i,"");

但是,根据浏览器中的正则表达式实现,它可能会不稳定,所以我宁愿有更强大的东西,特别是根本没有获得第一行。

TIA有任何建议 – 希望我能说清楚。

编辑:

clone()children()contents()结合使用,让我更进了一步。 但是,这两个也将删除第一个文本节点,留下两个空BR

 $("div.teaser").each(function() { var teaser = $(this).clone().children().not("img"); var teaser = $(this).clone().contents().not("img"); }); 

OTOH filter("img")find("img")not("img")后跟remove()删除除了IMG之外的所有东西,除了not()

 var teaser = $(this).clone().find("img").remove(); 

编辑2:

总结一下:

这是@karaxuna建议的解决方案。 重新分配变量很重要。

 var teaser = $(this).clone(); teaser.find("img,br:first").remove(); teaser = $.trim(teaser.html()); 

在做一些进一步的阅读以更好地理解失败背后的逻辑和最终的解决方案时,我得到了一个线索,让它稍微更加明显

 var teaser = $(this).clone(); teaser = $.trim($("img,br:first",teaser).remove().end().html()); 

线索是添加到$()选择器的范围或上下文。 在这里使用是很熟悉的,但我从来没有想过使用var。 此外, end()将使remove()仍然一直到DOM …

当然, $.trim技术上没有必要,HTML无论如何都会忽略空行。

所以包括正则表达式的上述解决方法至少有三种方法可以去 – 有点让我想起Perl;)

感谢@karaxuna和@Ravi分享他们的经验和想法!

不需要html()

 var teaser = $(".teaser").find("img").remove(); 

编辑:

试试这个:

 var teaser = $(".teaser").clone(); teaser.find("img").remove() // use teaser 

如果你想删除整个HTML。 那么你可以使用empty()方法

 $(".teaser").empty(); 

如果您只删除图像。 然后

 $(".teaser").find("img").remove(); 

已经晚了,但试试这个$('img',$('.teaser')).remove().end().clone()