使用jQuery在标记后隐藏文本

我想隐藏标签后的某些文字。

我的HTML是:

Living Room: Yes
Kitchen: No

jQuery的:

 $($('.listing_detail strong')[0].nextSibling).wrap(''); 

上面的jQuery只删除第一个元素的文本,而不是两个。

如何修改它以便从两个元素中删除文本。

小提琴

只需考虑循环遍历元素并通过each()函数隐藏每个元素的下一个兄弟:

 // Loop through each strong element $('.listing_detail strong').each(function(){ // Find it's next sibling and wrap it $(this.nextSibling).wrap(''); }); 

 $('.listing_detail strong').each(function(){ $(this.nextSibling).wrap(''); }); 
  
Living Room: Yes
Kitchen: No

为什么不使用.each().each()隐藏它们?

 $('.listing_detail strong').each( function(){ $($(this)[0].nextSibling).wrap(''); }); 

为什么不简单

 $('.listing_detail strong').hide(); 

还添加此项以从第二个元素中删除文本:

 $($('.listing_detail strong')[1].nextSibling).wrap(''); 

所以它将是:

 $($('.listing_detail strong')[0].nextSibling).wrap(''); $($('.listing_detail strong')[1].nextSibling).wrap(''); 

试试这个:

 $($('.listing_detail strong')[0].nextSibling).wrap(''); $($('.listing_detail strong')[1].nextSibling).wrap(''); 

我认为问题是$(’。listing_detail strong’)上的[0]选择器。 使用像’forEach’这样的遍历方法。 https://jsfiddle.net/d4gyv6ed/12/

 $('.listing_detail strong').each(function(index){ $(this).siblings().wrap(''); }); 

如果你不需要索引,最好不要把所有问题搞得一团糟。 像这样更新你的标记:

 
Living Room:
Yes
Kitchen:
No

然后使用jQuery执行此操作:

$(".hide-this-tag').hide();

或者只是简单地使用css:

 .hide-this-tag { display:none; } 

如果您要查找的只是特定标记内的文本节点,则无论文本节点在标记内的位置如何,这都是最有效的方法。

尝试使用.contents().filter()方法和this.nodeType == 3如下所示:

 $('.listing_detail').contents().filter(function() { return this.nodeType == 3; }) .wrap(''); 
  
Living Room: Yes
Kitchen: No

我要做的是创建一个具有隐藏属性的CSS类,并使用您的jQuery将它们添加到容器中。

这使您可以轻松地在将来添加和删除类。

这应该可以帮助你做到这一点

https://api.jquery.com/addclass/

并将其应用于多个div使用jquery中的每个函数

https://api.jquery.com/each/