2011-10-21 86 views
-1

我有一个帖子列表,我想删除所有文本/ HTML内容,除了内容设置为“strong”。使用JQuery过滤HTML内容但排除某些元素

原始

<li id="post"> 
    <p> 
     <strong>Reality</strong> 
    </p> 
    <p> 
     Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. 
    </p> 
</li> 
<li id="post"> 
    <p> 
     <strong>Buzz</strong><br> 
     <br> 
     Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. 
    </p> 
</li> 
<li id="post"> 
    <p> 
     <strong>Innovation</strong><br> 
     <br> 
     Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. 
    </p> 
</li> 

所需的结果

<li id="post"> 
     Reality 
</li> 
<li id="post"> 
     Buzz 
</li> 
<li id="post"> 
     Innovation 
</li> 

我怎么可以这样使用JQuery?

+2

仅供参考,ID的应该是唯一的,所以你或许应该改变ID = “发帖” 类= “后”。 –

+1

您的接受率很高! ;) –

回答

0

我的解决方案将是使选择所有强$(“强”),选择然后删除所有李时珍然后。每个项目在$(“强”),追加其内新李。


更新:

你可以试试这个:http://jsfiddle.net/6awfe/

$("li#post").each(function() 
    { 
     $(this).html("[strong start tag]" + $("strong", this).html()+"[strong end tag]"); 
    }) 
0

我的解决方案是制作一个选择器,选择所有strong $(“strong”),然后删除所有li,然后在$(“strong”)中添加每个项目,并将其添加到新的li中。

1

下面的代码按预期工作。 替换id="post"class="post" !!

小提琴:http://jsfiddle.net/GfsCB/

$("li.post").each(function(){ 
    var filtered = $("<li>").append($("strong", this).text()) 
    $(this).replaceWith(filtered); 
}); 
  1. 循环每一个<li>项目。
  2. 创建一个新的<li>元素,并添加所有<strong>元素
  3. 的文字内容由刚刚创建<li>元素(filtered)替换当前所选<li>元素。
0

这应该让你对你的方式:

var htmlText = ""; 
$('.post').find('strong').each(function() { 
    htmlText += "<li class=\"post\">" + $(this).text() + "</li>"; 
}); 

alert(htmlText); 
0
$('.post').each(function(){ 
    $(this).html($('strong', this).text()); 
}); 

更改ID = “发帖” 类= “邮报” 的人也状态。

0

假设你要改变id='post'class='post'id S的关系是唯一的):

$("li.post").each(function() { 
    $(this).text($(this).find("strong").text()); 
}); 

这保留相关联的列表项的所有属性,只替换内容。

演示:http://jsfiddle.net/BRnZh/