2016-11-18 54 views

回答

0

$('p:contains("#")').each(function() { 
 
    var tags = $(this).text().split(' '); 
 
    var wrapped_tags = ''; 
 

 
    tags.forEach(function(tag) { 
 
     wrapped_tags += '<span class="someClass">'+tag+'</span> '; 
 
    }); 
 

 
    $(this).html(wrapped_tags); 
 
});
.someClass { 
 
    color:red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>#tag1 #tag2</p>

+0

这也将包裹非“标签”(虽然不明确的问题开始的任何字如果只有标签或混合) –

+0

@ freedomn -m是的,我认为op意味着有很多pharagraps,其中一些只有里面的标签 – Sojtin

+0

@ freedomn-m无论如何,您的答案是更好 – Sojtin

2

您可以使用.html()以及通过当前值的回调并使用正则表达式:

#\w+\b 

这意味着:匹配以#

$("p").html(function(index, html) { 
 
     return html.replace(/(\#\w+\b)/g, "<span>$1</span>") 
 
     }); 
 
     
span { color: orange }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>#tag1 #tag2</p> 
 
<p>Here's another #tag3</p>